Repository navigation
Type parameters with an Ordered bound - #272
Merged
Merged
Conversation
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]>
Deploying dang with
|
| 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 |
vito
force-pushed
the
ordered-type-params
branch
from
November 8, 2026 23:53
591724b to
a27ec59
Compare
vito
force-pushed
the
ordered-type-params
branch
from
November 9, 2026 17:37
a27ec59 to
ce3fc7d
Compare
vito
marked this pull request as ready for review
November 9, 2026 17:39
vito
force-pushed
the
ordered-type-params
branch
from
November 9, 2026 17:42
ce3fc7d to
6c5aec6
Compare
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
force-pushed
the
ordered-type-params
branch
from
November 10, 2026 00:08
6c5aec6 to
86703a1
Compare
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]>
This was referenced Nov 10, 2026
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.
Adds explicit type parameter lists with an
Orderedbound, so users can write their ownsort/sortBywith compiler-checked call sites, and replaces #258'sBuiltinDef.Checkhook with the same bound.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.callCheckhook #258 adds, as the maintainer asked.Syntax
name[a, k: Ordered](...)on function and method declarations (TypeAndArgsAndBlockField/TypeAndBlockField), ported from thegenericsbranch'sTypeParamList. Bound grammar isTypeParam (':' 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.Orderedused as a type.analysis.Complete's details, viadang.FormatFunctionType) show a function type's bounds (largest: [a: Ordered](x: a!, y: a!): a!).NamedTypeNode.Inferon a name that isn't a type: a qualified name is anUnresolvedTypeError; otherwise a constraint name gives the "constraint, not a type" error, then the Prelude'sDecodedresolves, thenUnresolvedTypeError.Semantics
whyUnorderedand nothing else. It is the predicate behind the bound,<,.sortand.sortBy.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 := bboundsb, anda := [c]!makescthe non-null form of a bounded variable.ComposeandmergeTypescheck merges too. A bound that fails is ahm.ConstraintError, and composite unification reports that error rather than "cannot use X as Y". The deferred cases (mySort([])then+= [person], areduceaccumulator, an if/else merge) fail where the type is learned.hm.RegisterConstraint(name, host)gives each constraint its own bit (4 slots). On the dang side,BuiltinConstraintis 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, soNumericshould only need a new entry plus operator wiring.< > <= >=take every Ordered type (enums, booleans, lists, records, scalars), evaluated with stdlib: add stable sort and sortBy to lists #258'sorderer. The int/float/string fast paths are kept, so NaN behaves as before. Both operands are checked.a!compares and satisfies other bounds, includingxs.sorton[a!]!. An unboundedadoesn't, and the error says to declare the bound. A bare boundedamay be null, so<refuses it.sort's element variable andsortBy's key (k!) are bounded.&xs.sortBycalled later is now checked at type-check time, where stdlib: add stable sort and sortBy to lists #258 checked it at runtime.Maintainer decisions
[a: Ordered](xs: [a!]!)bindsatoIntfor[Int!]!(asa!does today), and<rejects nullable values where they're compared. The alternative, where a boundedais itself non-null, would make the natural[a!]!signature unusable. A list method's bounded elementatakes its receiver as[a!]!.hm.TypeVariable, not a wrapper type likeNullableTypeVariable. 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.pick(x: Int!).if (c) { [].sort } else { [person] }merged.idaliased tosymbol, with a declared GLR conflict. Otherwisexs[i]statements stopped parsing. A side effect: an unclosed${in a multi-line template is now diagnosed as a missing}(golden updated).let x 42keeps its message via a smallparse_errors.gotweak.k!rejects it before the bound sees it.Not done (follow-ups)
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.[{{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.+=, 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.sortBycalled later, andDecodeddata rejected by the bound (ordered_decoded_compare:<;ordered_bound_decoded_argument: ak: Orderedargument).Ordered" section intypes/nullability.md;reference/grammar.md,language/operators.md,data/collections.mdandtypes/enums-scalars.md; and the dang-language skill (types, syntax, objects, stdlib).