| Crates.io | bhc-index |
| lib.rs | bhc-index |
| version | 0.2.1 |
| created_at | 2026-01-25 17:29:59.642047+00 |
| updated_at | 2026-01-25 18:23:31.193393+00 |
| description | Typed indices for efficient and safe indexing |
| homepage | |
| repository | https://github.com/raskell-io/bhc |
| max_upload_size | |
| id | 2069137 |
| size | 21,381 |
Type-safe indices and indexed collections for the Basel Haskell Compiler.
This crate provides a pattern for creating type-safe indices that prevent mixing up indices from different collections. This is crucial in a compiler where many different ID types exist (expression IDs, type IDs, variable IDs, etc.).
| Type | Description |
|---|---|
Idx |
Trait for typed indices |
IndexVec<I, T> |
A vector indexed by a typed index |
IndexMap<I, T> |
An index-based map (alias for IndexVec<I, Option<T>>) |
use bhc_index::define_index;
define_index! {
/// Index into the expression arena.
pub struct ExprId;
/// Index into the type arena.
pub struct TypeId;
}
// These are now distinct types - can't mix them up!
let expr_id: ExprId = ExprId::new(0);
let type_id: TypeId = TypeId::new(0);
// This won't compile:
// let bad: ExprId = type_id;
use bhc_index::{IndexVec, define_index};
define_index! {
pub struct NodeId;
}
let mut nodes: IndexVec<NodeId, String> = IndexVec::new();
// Push returns the typed index
let id1 = nodes.push("first".to_string());
let id2 = nodes.push("second".to_string());
// Index with the typed ID
assert_eq!(nodes[id1], "first");
assert_eq!(nodes[id2], "second");
// Iterate with indices
for (id, node) in nodes.iter_enumerated() {
println!("{:?}: {}", id, node);
}
ExprId where a TypeId is expectedExprId(42))The define_index! macro generates indices with:
Clone, Copy, PartialEq, Eq, PartialOrd, Ord, HashDebug and Display implementationsu32 and usizeSerialize and Deserialize implementationsIdx trait implementationu32 internally (supports up to 4 billion items)IndexVec is a thin wrapper around Vec with typed indexingbhc-ast - Uses typed indices for AST node IDsbhc-hir - Uses typed indices for HIR definitionsbhc-core - Uses typed indices for Core IR bindings