The public types and algorithms are ordinary mojito .mojo declarations rather
than compiler-owned collection variants. The core implementations still use a
few narrow compiler-supported storage and construction seams, notably
UnsafePointer storage operations, literal/prelude hooks, and the private
__RuntimeTuple pack carrier. Together they are the north-star proof that the
language is expressive enough to author its own collections and small generic
algorithms.
The preferred import shape follows Mojo's std package layout:
from std.collections.list import List
from std.collections.set import Set
from std.collections.dict import Dict
from std.collections.optional import Optional
from std.math import floor, ceilA program always imports the library as std, wherever its search roots
point, as upstream's toolchain does.
std/collections/array.mojo— a fixed-sizeArray[T: AnyType, length: Int]backed by anUnsafePointer[T], with conditionalCopyable/Movable/Deinitable/Equatable/Iterable/IterableOwned/Writableconformances. Construction is the checker-driven variadic literal constructor ([a, b, c]displays), keywordfill,copy:, anddeinit move:; it is neitherImplicitlyCopyablenorDefaultable. Indexing is by-reference__getitem__only (no__setitem__, matching upstream Array);__len__returns the comptimelength, while the private_sizefield exists so the owned iterator can neutralize the source's destructor. Borrowed iteration mirrors_ListIter(_ArrayIterholdsref[iterable_origin] Array[T, length]); owned iteration moves the buffer into_ArrayOwnedIter, whose methods are where-gated so theT: AnyTypetemplate stays checkable.std/collections/list.mojo— a generic, growableList[T]backed by anUnsafePointer[T], with the full value-type lifecycle (ordinary__init__,__init__(..., copy:), and__init__(..., deinit move:)), subscript read/write (__getitem__/__setitem__),__len__, and the iterator protocol (__iter__(ref self)→ a borrowing_ListIter[iterable_mut: Bool, //, T, iterable_origin: Origin[mut=iterable_mut]]holdingref[iterable_origin] List[T], whose typed-raising__next__yieldsref[iterable_origin] Telement references; the iterator's__len__serveslen()and never drives a loop). Exhaustion raisesStopIteration. Growth reallocs the buffer._get_copy(index)is a library-private, non-overloaded value accessor used by nested collection implementations until a reference-returning subscript can retain its full selected-call contract as a chained receiver/place in typed MIR. Ordinary public value reads already copy through the returned reference, explicitrefbindings retain the alias, and public indexing remains__getitem__.std/range.mojo— current Mojo's private range family (_ZeroStartingRange/_SequentialRange/_StridedRange[dtype: DType = DType.int]), each its own borrowed typed-raising iterator overScalar[dtype]elements, returned by the bundled Intrangeoverloads; scalar arguments reach the same structs through checker-inferred dtype specialization. Length and Int indexing run; containment, formatting,reversed(),bounds(), and float strided ranges are recorded subset gaps.std/builtin/tuple.mojo— the public heterogeneousTuple[*Ts], with current__getitem_param__indexing and element-conditional lifecycle, comparison, formatting, concatenation, reversal, and consuming APIs. Its__RuntimeTuple[*Ts]field is compiler-private heterogeneous pack storage; public Tuple is nominal and is not a method-free runtime iterable. Its default initializer stores each element's default construction to that storage, available where every element isDefaultable.std/builtin/len.mojo— upstream'sSizedandSizedRaisingtraits, each requiring__len__, and upstream'slenoverload set over them (an@inline(.always)Sizedoverload, a raisingSizedRaisingone, and an@unavailableone over a string); the prelude exports all three. A struct conforms by declaring one, and the compiler-modelledSIMDscalars, tuples, and packs conform as the upstream structs they stand in for declareSized.std/builtin/comparable.mojo— upstream'sEquatableandComparable(Equatable)traits:__ne__defaulted through__eq__, and__gt__,__le__, and__ge__through__lt__; the prelude exports both. Upstream's reflective__eq__default is a stand-in the compiler synthesizes per conformer until its body can read each field throughfield_ref(R1481), so__eq__stays a requirement here. The compiler-modelled scalars andBoolconform to both, andDTypetoEquatable, as the upstream structs they stand in for declare.std/builtin/bool.mojo,std/builtin/int.mojo,std/builtin/floatable.mojo, andstd/builtin/identifiable.mojo— upstream's conversion traits:Boolable,Indexer,Intable,IntableRaising,Floatable,FloatableRaising, andIdentifiable, whose__isnot__defaults through__is__; the prelude exports all seven. The compiler-modelled scalars conform as the upstream structs they stand in for declare:SIMD,Bool, and the literals areBoolable;SIMD,Bool, and the numeric literalsIntable; onlyBoolandFloatLiteralareFloatable;SIMDandIntLiteralareIndexer. Only a scalarSIMDisIntable, and only an integral oneIndexer, since upstream's methods assert as much (R1397). A scalar answers a requirement through its builtin conversion.bool.mojoalso holds upstream'sSIMDoverloads ofanyandall, which the prelude exports; theIterableoverloads wait on R1605.std/builtin/simd_length.mojo— upstream'sSIMDLength, verbatim, the type ofSIMD's width: a wrapper of the MLIRindexthat a literal or anIntconverts to, and that converts to anySIMDthrough the compilerSIMD's@implicit __init__(SIMDLength). The prelude exports it.std/builtin/int_literal.mojoandstd/builtin/float_literal.mojo— upstream'sIntLiteral[value]andFloatLiteral[value]structs, in part: an explicit application over a literal's.valueconstructs one, and the members that read its!pop.int_literalor!pop.float_literalattribute (__mlir_index__,__int__,__int_literal__,is_nan,is_neg_zero) run as at the pin, andFloatLiteral's__float__,write_to, andwrite_repr_toreadFloat64(self),SIMD's declaredFloatLiteralinitializer. A literal4is the applicationIntLiteral[4], which the compiler holds as its literal type, and a bareIntLiteralparameter is upstream's per-callIntLiteral[x.value]. The prelude exports both.std/builtin/string_literal.mojo— upstream'sStringLiteral[value]struct, in part: the type of a string literal ("ab"isStringLiteral["ab"]) and of an explicit application, with the members that read its!kgen.stringthroughpop.string.size,pop.string.address, and#kgen.param.identical. The compiler holds an application as its literal type (roadmap R1660), and a bare run-timeStringLiteralargument is still a value-less compiler type (R1658). The prelude exports it.std/memory/unsafe.mojo— upstream'sbitcastandpack_bitsoverpop.bitcast, re-exported bystd.memory;std/builtin/dtype.mojobundles_uint_type_of_width,_integral_type_of, and_unsigned_integral_type_of.std/builtin/value.mojo— upstream'sDefaultable,RegisterPassable, andTrivialRegisterPassabletraits; the prelude exports all three.TrivialRegisterPassablerefinesDeinitable,ImplicitlyCopyable,Movable, andRegisterPassable, so a struct declaring it is copyable.Defaultable.__init__stays a requirement until a trait default can constructselffield by field, as upstream's reflective default does (R1119). The compiler-modelled scalars,Bool,NoneType, andDTypeconform as the upstream structs they stand in for declare.std/builtin/_stubs.mojo— upstream'sparamfor_has_next,paramfor_next_iter, andparamfor_next_value, which step acomptime foriterator at compile time. The prelude links them for their bodies: the compiler names them by module path, and no user spelling reaches them.std/builtin/builtin_slice.mojo— upstream'sSlice, the threeslice(...)functions,ContiguousSlice, andStridedSlice, each struct with the__slice_literal__constructor a slice literal calls for a parameter of its type;Slicewrites throughFormatStruct/Named, the two kinds delegatewrite_to/write_repr_toto it, andindicesis two-element forContiguousSlice;StridedSliceconverts implicitly from aSlice. The prelude bindsSliceandslice; only an import binds the two kinds.std/builtin/variadics.mojo— upstream's_MLIR.KGENTypeType(!kgen.type) and_MLIR.KGENParamListType[elt_type: Self.KGENTypeType]raw-list alias,ParameterList[type: AnyType, //, values: _MLIR.KGENParamListType[type]], the zero-sized value a homogeneous value pack is when read at run time (ParameterList[vs.values]()), and its_ParameterListIter. Its elements live in a constant array laid out once per program;get_spanaddresses it through the compiler-private__param_list_address[values](), admitted only in this module, where upstream callsglobal_constant. It isWritablewhere its element type is;write_repr_towrites upstream'sFormatStructtext directly.std/collections/optional.mojo— a genericOptional[T]using zero-or-one value storage, including an empty constructor for generic absent values.std/iter.mojo— minimal self-hostedIterator,Iterable, andIterableOwnedproof traits. They expose associated compile-timeElementfacts.IterableOwneduses current Mojo's monomorphicIteratorOwnedType(a consuming iterator owns its storage, so it needs no origin). BorrowedIterableuses Mojo's origin-parameterizedIteratorType[iterable_mut: Bool, //, iterable_origin: Origin[mut=iterable_mut]]with__iter__(ref self) -> Self.IteratorType[origin_of(self)]; the bundled member templates stay origin-erased; every bundled borrowed iterator carries its origin as an erased struct parameter, borrows its source, and yields element references declared at_get_owned_interior["element"]granularity, resolved to the source's mutability at each loop site. Mapping mutation during iteration is lazily rejected; view iterators snapshot at the call.std/format/__init__.mojo— upstream'sWriterandWritabletraits:Writer'swrite_stringrequirement and the defaultwrite[*Ts: Writable]that writes each argument through itswrite_to, which a conformer may override, andWritable'swrite_to/write_repr_torequirements. The prelude exports both. Upstream's reflective defaults are synthesized per conformer (R1461), writing each field through_reflection_write_field_to, which every module hosting a defaulted conformer imports.std/collections/set.mojo— a generic, list-backedSet[T, H: Hasher = default_hasher]forHashable & Equatable & Copyable & Movableelements (upstream's KeyElement bound and hasher parameter; the dense list preserves insertion order and never hashes). It supportsadd, membership throughin/__contains__,len, and borrowed reference-yielding iteration through the backing list's borrowed_ListIter. It conforms toIterable.std/collections/dict.mojo— a generic, hash-backed, insertion-orderedDict[K: Hashable & Equatable & Movable, V: Movable, H: Hasher = default_hasher]: dense entries (each caching itsUInt64hash underH) preserve order whileList[List[Int]]buckets index them by the hash's low bits, doubling when the load factor reaches one. It supports subscripts, overloadedget, membership, key iteration, self-iterable non-indexablekeys/values/itemsborrowing views, lazily drainingtake_items, publicDictEntry, and value-semantic copying. A missing subscript raisesError("missing key").std/collections/string_dict.mojo— the insertion-ordered owningStringDict[V]used for homogeneous**kwargs; a call builds it through its empty constructor and one_insertper collected keyword, as upstream's call does, and passes it, or the dictionary a**kwargs^forwards, whole.std/algorithms.mojo— small generic helpers that exercise comptime-guided library code: type predicates, CTFE-computed constants, value parameters, and associated compile-time facts. It includesfirst_or[C: Iterable], which consumesC.Elementthrough an opaque iterable bound.std/hash/— current Mojo's hashing package:hash.mojois theHashablehome and defineshash[T: Hashable, //, HasherType: Hasher = default_hasher](x) -> UInt64and the bytes overloadhash[HasherType](bytes: ImmPointer[UInt8, _], n: Int);hasher.mojois theHasherhome and definesdefault_hasher(the zero-keyedAHasher[SIMD[DType.uint64, 4](0)]) anddefault_comp_time_hasher(Fnv1a);_ahash.mojo(the keyedAHasher[key: U256],hash_seeded,hash_seeded_bytes) and_fnv1a.mojoport the two algorithms in upstream's_update_with_simd(mut self, value: SIMD[_, _])spelling overto_bits/.length(a 32-bit-limb folded multiply stands in for the 128-bit product; the rotation is spelled inline).hash.mojodeclares upstream'sHashable(the prelude exports it) andhasher.mojotheHashertrait with Mojito's requirement set (R25); the reflective__hash__default is still synthesized by the compiler (R1481). The compiler instantiates the_update_with_simdtemplate per hashed vector type, whichstd.simd'sSIMD.__hash__calls with-0.0folded and which takes aBoolorDTypeleaf asScalar[DType.bool]orUInt8, and a string's bytes as aSpan[Byte, _](_update_with_bytes). The containers (List,Array,Set,Dict,Optional,Variant,Tuple) conform toHashableconditionally in upstream's bodies. Values match the audited head on both backends.std/bit.mojo—rotate_bits_left[shift: Int](x: UInt64), thestd.bitsubset (aUInt64instance of upstream's SIMD-generic helper).std/math/— upstream'sstd.mathpackage:__init__.mojore-exports the ported names,constants.mojoholdspi,e,tau, andlog2e(from std.math.constants import log2e; the package does not re-export it), andmath.mojoholds upstream's seven operation traits (Absable,Roundable,DivModable,Ceilable,Floorable,Truncable, andCeilDivable), the rounding helpersfloor/ceil/trunc/ceildiv, each generic over its trait,copysign,ldexpover_ldexp_impl(with its AVX-512scalefarm),expover_exp_impland_exp_taylor'spolynomial_evaluate, and the libm constants_SQRT2,_LN2,_LN2_HI_F64, and_LN2_LO_F64.polynomial.mojoholdspolynomial_evaluateand_horner_evaluateover compile-timeSpancoefficients (from std.math.polynomial import polynomial_evaluate; the package does not re-export it). The package also re-exportsstd.utils.numerics'inf,nan,isnan,isinf, andisfinite, whose classifiers callllvm.is.fpclass. The prelude exportsAbsable,Roundable,abs,max,min, andround, as upstream's does; the rest must be imported (from std.math import floor).divmodis still a compiler builtin (R1458). EverySIMDdeclaresAbsable,Ceilable,CeilDivable,DivModable,Floorable,Roundable, andTruncableinstd/simd.mojo, with upstream's__ceildiv__,__divmod__,__mod__,__rmod__, and__imod__bodies.std/span.mojo— the prelude-exported borrowed viewSpan[mut: Bool, //, T: AnyType, origin: Origin[mut=mut]](upstream's bound): a multi-element origin-bearing pointer (Pointer[T, origin._get_owned_interior["element"]]) plus a length, constructed fromref [origin] list: List[T]so the source stays lent while any copy of the view lives. Element access is a reference result with abort bounds; the strictContiguousSliceoverload returns a sub-view; there is no strided slicing. It isBoolable,Sized, and conditionallyWritable, with==/!=andinoverEquatableelements.List's ownContiguousSliceoverload returns aSpanover the list's owned elements, as upstream's does.std/os/— upstream'sospackage subset:os.mojo(sep,SEEK_*,listdirover a privateopendir/readdirstream read as glibcdirentbytes,mkdir/makedirs,remove/unlink,rmdir/removedirs, andabort(message)— the uncatchable trap crossing to the VM through the compiler-private_mojito_abortprimitive, which stdlib-internal trap sites call directly to avoid import cycles),env.mojo(getenv/setenv/unsetenv),pathlike.mojo(re-exports thePathLiketrait declared besideString),_linux_x86.mojo(the scalar-only_c_statrecord glibc's__xstat/__lxstatfill), andpath/path.mojo(exists,lexists,isdir,isfile,islink,getsize,is_absolute,join,split,basename,dirname,split_extension,splitroot,expandvars,expanduser). Every host call is upstream'sexternal_callover the closed libc table (std/ffi).std/io/—file.mojo(FileHandleover a raw descriptor andopen; both prelude names) andfile_descriptor.mojo(RawFileDescriptor, aWriterover a descriptor;print(file=)writes through it).std/sys/adds_io.mojo(stdin/stdout/stderras compile-timeRawFileDescriptorvalues). Because the prelude importsstd.io, every module on its import graph (std.os,std.sys,std.stat, ...) loads while the prelude bootstraps and must importStringexplicitly (from std.string import String);rangeis not visible there either.std/pathlib/—path.mojo(Path,cwd,DIR_SEPARATOR;joinpathiterates its pack and binds each view before/=, the shape both backends run).std/tempfile/—tempfile.mojo(gettempdir,mkdtemp,TemporaryDirectory;_get_random_namereads/dev/urandomuntilstd.randomlands).std/ffi/__init__.mojo— thec_*scalar aliases, theexternal_callbuiltin's import home,CStringSlice(declared instd/string.mojo, which loads first) andget_errnore-exports.std/sys/info.mojo— upstream'sCompilationTarget(current,_unknown,_has_feature, thehas_*x86, Neon, and RISC-V queries, the string-field getters_arch,_os,__triple, and__triple_arch, and the platform, Apple, accelerator, GPU, and OS predicates), the freeis_gpu,is_nvidia_gpu,is_amd_gpu,is_apple_gpu, and AMD families,simd_bit_width,simd_byte_width,is_32bit,is_64bit, and the layout queriessize_of,align_of,bit_width_of, andsimd_width_ofover KGEN'sget_sizeofandget_alignof. The queries read the!kgen.targetattribute the elaborator answers_current_target()with; the file's header lists what is still omitted and the roadmap entries that own it.std/sys/_libc_errno.mojo—ErrNo(String(err)renders glibc'sstrerrortext),get_errno,set_errno.std/stat/— theS_IF*mode constants andS_ISDIR/S_ISREG/S_ISLNK.std/time/time.mojo— the Ctimespecrecord_CTimeSpec.std/string.mojoalso hostsStringSpan[mut: Bool, //, origin](the canonical string view;StringSliceis a never-emitted annotation alias), upstream'sStaticStringalias (StringSpan[ImmStaticOrigin]; a literal binds aStaticStringcompile-time parameter through the@implicitliteral constructor, which the elaborator runs into a frozen view of the literal's bytes) and_GraphemeIter, the grapheme-cluster iterator behind ordinary String/StringSpan/StringLiteral iteration.std/collections/string/string_span.mojo— upstream's_get_kgen_string[string: StaticString, *extra: StaticString]()at its upstream module path, the!kgen.stringof the views' bytes, whichstd/sys/intrinsics.mojo'sllvm_intrinsicreads itsintrinthrough, andget_static_string, theStaticStringover that string. The rest of upstream's module, including theStaticString(_kgen)initializerget_static_stringcalls, lives instd/string.mojo.
Underscore-prefixed structs such as _ListIter are implementation details,
following the Python convention that Mojo currently inherits. DictEntry is
public, matching Mojo's item-view element. Mapping views are self-iterable,
non-indexable borrowing views that hold a loan on their source while they
live: mutating the mapping while a view is live is rejected, and value/entry
yields are read-only (a conservative subset of upstream's mut-following
value references).
The register VM executes the ordinary MIR produced for these declarations;
tests/self_host_test.rs links and runs them. Public List/Tuple runtime variants
have already been retired. The remaining private storage bridges are
documented in the architecture and roadmap.