Skip to content

Type parameters with an Ordered bound - #272

Merged
vito merged 16 commits into
stdlib-sort-byfrom
ordered-type-params
Nov 10, 2026
Merged

vito merged 16 commits into
stdlib-sort-byfrom
ordered-type-params

Conversation

@vito

@vito vito commented Nov 8, 2026 •

Copy link
Copy Markdown
Owner

Adds explicit type parameter lists with an Ordered bound, so users can write their own sort/sortBy with compiler-checked call sites, and replaces #258's BuiltinDef.Check hook with the same bound.

insertionSort[a: Ordered](xs: [a!]!): [a!]! {
  xs.reduce([]) { acc, x => acc.takeWhile { y => y <= x } + [x] + acc.dropWhile { y => y <= x } }
}
mySortBy[a, k: Ordered](xs: [a!]!, &key(item: a!): k!): [a!]! { xs.sortBy { x => key(x) } }

insertionSort([3, 1, 2])          # [1, 2, 3]
mySortBy(people) { _.name }       # ok
mySortBy(people) { _ }            # error at the block: cannot use Person! for `k: Ordered`: it has no order; ...

This PR and #258 have to merge together (or this one right after #258, with no release in between): it removes the BuiltinDef.Check / Select.callCheck hook #258 adds, as the maintainer asked.

Syntax

  • name[a, k: Ordered](...) on function and method declarations (TypeAndArgsAndBlockField / TypeAndBlockField), ported from the generics branch's TypeParamList. Bound grammar is TypeParam (':' Bound ('&' Bound)*)?. The parameter is a word and the bound a type name, so longer names and interface bounds can come later without a syntax change.
  • No list: type variables are implicit, as before. With a list: every signature variable must be declared, each declared one must be used, and duplicates are errors. Unknown bounds are errors, and so is Ordered used as a type.
  • The formatter prints the list. Hover and completion (the LSP's and analysis.Complete's details, via dang.FormatFunctionType) show a function type's bounds (largest: [a: Ordered](x: a!, y: a!): a!).
  • NamedTypeNode.Infer on a name that isn't a type: a qualified name is an UnresolvedTypeError; otherwise a constraint name gives the "constraint, not a type" error, then the Prelude's Decoded resolves, then UnresolvedTypeError.

Semantics

  • Ordered membership is stdlib: add stable sort and sortBy to lists #258's whyUnordered and nothing else. It is the predicate behind the bound, <, .sort and .sortBy.
  • The bound lives on the type variable as a flag bit, beside the rigid and weak bits, so every copy carries it: Freshen (call instantiation), Rigid (inside the body), weak variables, and the nullable form. Unification checks every binding of a bounded variable. When a variable is bound to an unknown, the bound passes to it: a := b bounds b, and a := [c]! makes c the non-null form of a bounded variable. Compose and mergeTypes check merges too. A bound that fails is a hm.ConstraintError, and composite unification reports that error rather than "cannot use X as Y". The deferred cases (mySort([]) then += [person], a reduce accumulator, an if/else merge) fail where the type is learned.
  • Constraint registry (for Numeric). hm.RegisterConstraint(name, host) gives each constraint its own bit (4 slots). On the dang side, BuiltinConstraint is a table entry holding the name, the membership predicate and the operators it enables. Bound parsing, the "constraint, not a type" error, the operators' domain and the "declare it [a: Ordered]" hint all go through the table, so Numeric should only need a new entry plus operator wiring.
  • Operators: < > <= >= take every Ordered type (enums, booleans, lists, records, scalars), evaluated with stdlib: add stable sort and sortBy to lists #258's orderer. The int/float/string fast paths are kept, so NaN behaves as before. Both operands are checked.
  • Generic bodies: a bounded a! compares and satisfies other bounds, including xs.sort on [a!]!. An unbounded a doesn't, and the error says to declare the bound. A bare bounded a may be null, so < refuses it.
  • Builtins: sort's element variable and sortBy's key (k!) are bounded. &xs.sortBy called later is now checked at type-check time, where stdlib: add stable sort and sortBy to lists #258 checked it at runtime.

Maintainer decisions

  1. Bounds ignore nullability. [a: Ordered](xs: [a!]!) binds a to Int for [Int!]! (as a! does today), and < rejects nullable values where they're compared. The alternative, where a bounded a is itself non-null, would make the natural [a!]! signature unusable. A list method's bounded element a takes its receiver as [a!]!.
  2. The bound is a bit on hm.TypeVariable, not a wrapper type like NullableTypeVariable. It follows the same approach (enforced at binding, merged when variables meet), but as a bit it survives every existing copy and substitution path without new cases. Ids now get 33 bits and wrap rather than spill into flag bits.
  3. A bounded method can't implement an interface's unbounded generic method (arguments and block are checked with the interface's variables rigid). It can still implement a concrete Ordered signature like pick(x: Int!).
  4. An if/else whose branches fail a bound is an error at the else branch, not a union. Before this PR, if (c) { [].sort } else { [person] } merged.
  5. Parameter names are single lowercase letters for now. This is checked at type-check time, with an error, not in the grammar.
  6. Tree-sitter reads a generic name as an id aliased to symbol, with a declared GLR conflict. Otherwise xs[i] statements stopped parsing. A side effect: an unclosed ${ in a multi-line template is now diagnosed as a missing } (golden updated). let x 42 keeps its message via a small parse_errors.go tweak.
  7. A nullable sortBy key now says "block argument body may be null (Int), but must not be: supply a default with ??", since k! rejects it before the bound sees it.

Not done (follow-ups)

  • Interface header fields (interface I { m[a: Ordered](...) }) can't declare type parameters, so the docs' stdlib signature cards don't show bounds.
  • analysis.Member.Signature() (doc/members output) is built from argument strings and doesn't show bounds.
  • Editor highlight queries (zed/nvim submodules) don't style type parameter lists yet.
  • Pre-existing, unrelated: a return annotation with a record of rigid variables ([{{first: a!}}!]!) fails with "declared X, inferred X".

Tests and docs

  • tests/test_type_params.dang: insertionSort, mergeSort and a user sortBy over ints, strings, booleans, enums, lists and records; methods, nested functions, interfaces and deferred bounds.
  • Error goldens: bad argument, bad block, deferred (+=, reduce, if/else), < on an unbounded or nullable variable, an unbounded variable passed to a bounded function, undeclared, unused, duplicate, unknown bound, Ordered as a type, bounded implementations of unbounded interfaces, union operands, mixed and nullable sortBy keys, &xs.sortBy called later, and Decoded data rejected by the bound (ordered_decoded_compare: <; ordered_bound_decoded_argument: a k: Ordered argument).
  • hm unit tests, including two constraints merging; a formatter test; a tree-sitter corpus; an LSP hover case.
  • Docs: a new "Type parameters and Ordered" section in types/nullability.md; reference/grammar.md, language/operators.md, data/collections.md and types/enums-scalars.md; and the dang-language skill (types, syntax, objects, stdlib).

vito added 11 commits November 8, 2026 22:07
Add an Ordered bound to type variables, kept as a flag bit beside the rigid
and weak ones so that every copy of a variable carries it: Freshen's (a
call's instantiation), Rigid's (the parameter inside its body), a weak
variable's (a binding's unknown part) and its nullable form's.

Unification checks a binding of a bounded variable against the bound and
passes the bound on to the variables of what it is bound to: binding it to
another variable bounds that one, and binding it to [c]! makes c the non-null
form of a bounded variable, since an Ordered list's elements are never null.
A variable left unknown keeps its bound until some later unification learns
its type. Merging two bindings in Compose checks the merge too. The bound
ignores nullability, so `[a: Ordered](xs: [a!]!)` binds a to Int for an
[Int!]!.

hm knows no concrete types, so which ones are Ordered is the host's to say,
through OrderedHost. A failing bound is a ConstraintError, which composite
unification reports as is rather than as the enclosing types not unifying.

Signed-off-by: Alex Suraci <[email protected]>
A function or method may declare its type parameters explicitly, each with an
optional bound: `sortBy[a, k: Ordered](xs: [a!]!, &key(item: a!): k!)`.
Without a list, type variables stay generic implicitly, as before; with one,
it must declare each variable of the signature exactly once and use every one
it declares. Ordered is the only bound so far, but the grammar takes any type
name there (and a word for the parameter), so interface bounds and longer
names can come without a syntax change. Ordered written as a type is an error
that says how to bound a parameter instead.

Ordered is exactly what sort and sortBy order, with whyUnordered as the one
definition: it is now the bound's host predicate too. A bounded parameter is
Ordered inside its function, so its non-null values compare with < > <= >=
and it satisfies another function's bound; an unbounded one doesn't, and the
error says to declare the bound. At a call, the bound travels with the
instantiated variable, so a bad type is an error at the argument or block
that supplies it, or, when the call leaves it unknown (`mySort([])`, a reduce
accumulator), wherever it is learned.

The ordering operators now take every Ordered type (enums, booleans, lists,
records and scalars too, not just numbers and strings), evaluated with sort's
orderer, so Ordered is what < accepts as well as what sort accepts.

The formatter prints the list, and hover and completion show a function
type's bounds. Tree-sitter reads a generic function's name as an id (aliased
to a symbol node), which keeps a statement starting `name[` open between a
declaration and indexing a value. Its error recovery changes with it: an
unclosed `${` in a multi-line template is now reported as a missing `}`.

Signed-off-by: Alex Suraci <[email protected]>
Replace #258's BuiltinDef.Check hook, and the Select.callCheck plumbing that
ran it, with the Ordered bound in the methods' signatures: sort's element
variable is Ordered, and sortBy's block returns a k! with k Ordered. The
bound is what user code gets from `[a: Ordered]`, so the builtins and a
user's own sort are checked by one mechanism, with whyUnordered as the
predicate.

A bounded element variable takes its receiver as [a!]!: orderedElems checks
the elements on selection, and bounds them instead when their type isn't
known yet, for good when they are a binding's. The key's bound now travels
with the method's type, so `&xs.sortBy` called later is checked at type-check
time too, where #258 left it to the implementation at runtime.

A block whose result may be null where a non-null one is expected (a
nullable sort key) now says so, rather than naming the two types.

Signed-off-by: Alex Suraci <[email protected]>
Add a section on explicit type parameter lists and the Ordered bound to the
type variables docs, the TypeParamList production to the grammar notes, and
both to the dang-language skill. The sorting docs and the skill's sort entry
now say that sort and sortBy are bounded by Ordered, and that a receiver
whose element type isn't settled yet is checked where it is learned rather
than at runtime; the comparison operators' entry lists every Ordered type.

Signed-off-by: Alex Suraci <[email protected]>
Merging two types (if/else branches, repeated bindings) fell back to a
common supertype or a union when a bound failed, losing the reason: a
sorted `[]` met with a list of objects widened to a union that failed later
with an internal-looking error, and argument merges said only that the lists
didn't unify. mergeTypes now returns the ConstraintError, and a conditional
reports it at the else branch.

A sortBy key that mixes types across branches failed to unify with k! before
the bound was ever checked, so it was reported as not matching a variable the
user never wrote; the block now reports the bound's reason ("it mixes types;
return one type from every branch"), as #258's check did.

Signed-off-by: Alex Suraci <[email protected]>
checkOrdering unified the operands and then checked only the left one, so
with a union on the right (`"a" < u`, u from mixed branches) the comparison
type-checked and failed at runtime, while `u < "a"` was an error. Check
both. A function value now reports that it has no order rather than that it
may be null.

Signed-off-by: Alex Suraci <[email protected]>
A type could implement an interface's generic method, `pick(x: a!, y: a!)`,
with a bounded one, `pick[a: Ordered](...)`. Callers through the interface
may pass any type, so the method's `<` then met values with no order at
runtime. Check each argument with the interface's type variables made rigid
and unbounded, so the bound must hold for every type they stand for; an
interface naming an Ordered type (`pick(x: Int!)`) is still implemented by
the bounded method.

Signed-off-by: Alex Suraci <[email protected]>
The operators page still said < compares only numbers and strings,
alphabetically.

Signed-off-by: Alex Suraci <[email protected]>
Ordered was hard-coded as one flag bit and one host hook. Make bounds a
small registry instead, so that the next built-in constraint (Numeric is
planned) slots in without reworking the machinery: hm.RegisterConstraint
takes a name and a ConstraintHost, and a type variable has a bit per
constraint (four slots, below the weak bit; fresh ids keep the 33 bits
below them, wrapping rather than ever setting one). Binding a bounded
variable checks every bound it carries, and binding two variables bounds the
result by both. Require(c, t) replaces RequireOrdered.

On the dang side, BuiltinConstraint is a table entry: its name, its
membership predicate (whyUnordered for Ordered), and the operators it gives a
bounded variable's values. Type parameter bounds, the "is a constraint, not a
type" error, the unknown-bound message, the ordering operators' domain and
their "declare it [a: Ordered]" hint, sort's bounded element variable and the
hover rendering all go through the table.

Signed-off-by: Alex Suraci <[email protected]>
checkImplementationBounds covered a method's arguments but not its block:
`best[a: Ordered](&mk: a!): a!` still implemented an interface's
`best(&mk: a!): a!`, whose callers may pass a block returning values with no
order. Check the block the same way.

Signed-off-by: Alex Suraci <[email protected]>
The scalars page still said they have no ordering; < and .sort compare them
by their string form.

Signed-off-by: Alex Suraci <[email protected]>
@vito
vito added this pull request to stack #273 November 8, 2026 23:04
@cloudflare-workers-and-pages

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

Copy link
Copy Markdown

Deploying dang with  Cloudflare Pages  Cloudflare Pages

Latest commit: 2297001
Status: ✅  Deploy successful!
Preview URL: https://5680c020.dang-3kk.pages.dev
Branch Preview URL: https://ordered-type-params.dang-3kk.pages.dev

View logs

@vito
vito force-pushed the ordered-type-params branch from 591724b to a27ec59 Compare November 8, 2026 23:53
@vito
vito force-pushed the ordered-type-params branch from a27ec59 to ce3fc7d Compare November 9, 2026 17:37
@vito
vito marked this pull request as ready for review November 9, 2026 17:39
@vito
vito force-pushed the ordered-type-params branch from ce3fc7d to 6c5aec6 Compare November 9, 2026 17:42
Pin that `<` on Decoded data and a Decoded argument for an Ordered type
parameter are compile errors, and update the sortBy golden now that its
key is a bounded parameter.

Signed-off-by: Alex Suraci <[email protected]>
@vito
vito force-pushed the ordered-type-params branch from 6c5aec6 to 86703a1 Compare November 10, 2026 00:08
vito added 4 commits November 10, 2026 00:11
The grammar notes and skill described type parameters by what they allow
"for now" and "so far" and what "can come later". Say what the grammar
reads and what it accepts.

Signed-off-by: Alex Suraci <[email protected]>
The guide and skill called Ordered the only bound "for now"; describe
the bound as it is.

Signed-off-by: Alex Suraci <[email protected]>
The grammar reference already allows `f[a, k: Ordered,]`, and the parser
accepts it; the skill's production now matches.

Signed-off-by: Alex Suraci <[email protected]>
Complete rendered a function's type with HMType.String(), dropping the
`[k: Ordered]` list the LSP's completion shows; it now uses
FormatFunctionType too.

Signed-off-by: Alex Suraci <[email protected]>
@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