Maps and sets (roadmap #17)
var counts = {} # Map[Str, Int], inferred
for w in split(text, " "):
if w in counts:
counts[w] = counts[w] + 1 # in place: nobody else holds `counts`
else:
counts[w] = 1
get(counts, "cat") # Option[Int]: None
for w in counts: ... # keys, in insertion order
let s = add(set([1, 2]), 3) # Set[Int]; union / intersection / difference
3 in s, "lo" in "hello", 2 in [1, 2] # `in` works on Map keys, Set, List and Str
Semantics
- Values, not references.
let c2 = remove(c, "and") leaves c unchanged. Copies share the table until one of them changes. A change to a table nobody else holds happens in place: the interpreter and VM use Rc::make_mut, and native code checks for rc == 1 and otherwise copies first.
- Insertion order for iteration,
keys, values and printing, as in Python. Replacing a value keeps the key's position. The order is part of the semantics, so output is deterministic in every engine. Tier-up by replay (#43) depends on that.
- Keys must be hashable with a lawful equality. The
Key trait is checked structurally: Int, Bool, Str, Unit, and lists and data types made of keys (so {[0, 0]: Red} works). A Float key is rejected, with the reason (NaN ≠ NaN, 0.1 + 0.2 ≠ 0.3). Functions, maps and sets can't be keys either. A Map's or Set's own type parameter is always a key, so impl Describe for Map[k, v] doesn't need where k: Key.
- **
m[k] on a missing key** is a runtime error (key "b" is not in the map), reported identically in every engine. Use get(m, k), which returns an Option, to avoid it.
- Inference. Map literals,
in, remove, for and indexing work out whether a value is a List, Map, Set or Str from how it's used. Indexing with a non-Int means it's a Map. word_counts : (Str) -> Map[Str, Int] and graph_reachable : (Map[a, List[a]], a) -> Set[a] where a: Key need no annotations.
- Equality ignores order (
{1: "a", 2: "b"} == {2: "b", 1: "a"}). Sets print as {1, 2}; the empty set prints as set() and the empty map as {}.
- Traits dispatch on Map and Set too.
Implementation
- Interpreter and VM:
src/collections.rs, an insertion-ordered table (entries plus a HashMap index, with tombstones and compaction). The interpreter also handles s = add(s, x) and s = remove(s, x) in place, as it does xs = push(xs, x).
- Native:
trine_rt.h has an open-addressing hash index over insertion-ordered entry arrays, a structural hash consistent with ==, copy-on-write, and compaction when more than half the entries are dead.
- Lowering. -
m[k] and m[k] = v on maps become the #mget and #mset builtins; the type checker records which index operations are on maps. - get becomes if k in m: Some(m[k]) else: None. - for k in m iterates keys(m). - add, remove and #mset take ownership of the collection, as push does. That ownership is what makes them update in place.
Evidence
- Golden program
examples/collections.tr covers word counts, graph reachability over a Map[Str, List[Str]], set algebra, list keys, Describe implemented for Map[k, v], and a 10,000-entry map. Output is identical in the interpreter, 4 VM strategies and native code, with 0 leaked objects and clean sanitizer runs. 99.3% of refcount overhead is removed, and building the map makes 10,037 in-place updates (test maps_update_in_place).
- Six error tests: a Float key, a wrong key type,
in on an Int, functions in a set, an ambiguous remove, and a missing key at run time.
- Fuzzer coverage. Generated programs build maps and sets with literals,
mput, remove, add, set algebra and keys-to-set. They read them with order-sensitive sums, which check insertion order, and with get, in, == and direct indexing (which can fail). Keys come from a small range, so repeats, replacements and removals happen often. 64% of generated programs use them outside the helpers. - 40,000 program cases ran clean (interpreter vs 5 VM strategies). - 800 native cases, 300 sanitized release-build native cases and 20,000 syntax mutations ran clean.
- Speed. The new
maps benchmark does 300k lookups and updates on a 50k-entry map plus 300k set inserts. It takes 38 ms natively against 105 ms in CPython, 2.8× faster, and both times include startup. At 1M operations it is 71 ms against 368 ms (5.2×).
Honest notes
- Slower than C or Rust hash maps. Every key goes through the generic structural hash and
rt_eq, with tagged 16-byte values. Specializing tables for Int and Str keys would be the next speed-up.
- Some generic code needs an annotation. A function that loops over a parameter and indexes it with the loop variable (
for k in m: m[k]) can't tell a Map from a List[Int] without one (m: Map[Int, Int]), and then defaults to the list reading.
- **No
items() yet.** Use for k in m: with m[k], or build pairs with a comprehension: [(k, m[k]) for k in m]; {k: v for ...} builds a map.
- One unexplained test failure.
bet3_schedules_never_change_results failed once during a full test run and could not be reproduced: 4 reruns, plus 360 schedule trials under heavy parallel load, all passed. Its reference run used the default trine run, which now goes through the cache and tier-up. It is now pinned to --interp, which is what it means to compare against. If the default path had a real fault there, the other cache tests and the stress runs didn't reproduce it.