Mojo nightly
This version is still a work in progress.
Language enhancements
-
if,comptime if, and__guardnow support semicolon-separated condition clauses that mix Boolean conditions andcasepatterns. Clauses evaluate left to right, and successful pattern bindings are available to later clauses and the successful path. -
Added the experimental
__guardstatement for early exits from Boolean conditions andcasepatterns. Itselsebody must not fall through, so bindings from a successful pattern remain in scope on the normal path. This is analogous to features in Rust and Swift, and also supportscomptime __guard. -
tryblocks now unify heterogeneous raised error types rather than selecting the first raised type. Mojo selects a common type when one exists, otherwise usesError. It emits a compile-time error when the raised types cannot be unified. -
withstatements now no longer copy when passed a reference to a context manager like inwith foo: pass. -
__exit__(self, error: E)now additionally supportsvar selfanddeinit self, similar to the non-error__exit__. -
You can bind a non-
Movablepayload from an rvalue enum or tuple subject with avarcase binding, enablingcase .Some(var value):andcase (var x, var y):without copies. This allowsmatchandif casestatements to work with non-movable and linear types, and reduces copies in general. -
You can destructure a tuple of transferred non-copyable values into a
varpattern without copies, such asvar (x, y) = (a^, b^). This includes movable types that are notCopyable. -
Comparisons now try the reflected method on the right operand when the left operand does not support the comparison. For example,
0 < valuecan callvalue.__gt__(0). -
matchnow warns when literal cases do not include a catch-all pattern, helping identify unmatched values. -
A closure that captures a value with an
UnsafeAnyOriginin its type, such as aPointer[Int, MutUnsafeAnyOrigin], now produces a warning. A closure does not keep the value behind such a capture alive, so Mojo can destroy that value before the closure runs. Capture a value with a tracked origin instead. -
Auto-parameterization now reaches
_holes nested inside other parameterized types, so an unbound parameter at any depth of an argument's type becomes an an implicit parameter of the function:def process(p: Optional[Pointer[Int, _]]): ... -
Mojo now allows unbound a parameter that has a default dependencies, the default value will later be refined when the unbound parameter is provided:
def depends_on_a[a: Int]() -> Int:return astruct NestedDeps[a: Int, b: Int = depends_on_a[a]()]:...# No longer a compilation errorcomptime Partial = NestedDeps[_]# Bound = NestedDeps[3, depend_on_a[3]()]comptime Bound = Partial[3] -
A call to a function that takes a variadic pack (
*args: *Ts) can now mix arguments and unpacked packs. The callee receives one pack with all the elements in order:def show[*Ts: Writable](*args: *Ts): ...def wrap[*Ts: Writable](*args: *Ts):show("[", *args, "]")show(*args, *args)Unpacking the same pack twice into a
mutpack argument, such asupdate(*args, *args), is an aliasing error. -
A conditional type
A if c else Bnow refines to the selected arm inside acomptime if c:branch, itselsebranch, and after acomptime assert c. You can call the arm's methods and read its fields without arebind:def describe[present: Bool](value: Int if present else NoneType):comptime if present:print("value:", value + 1) # `value` is an `Int` hereelse:print("empty")A value of the selected arm also converts to the conditional type, so you can return or pass it without a
rebind:def make[present: Bool]() -> Int if present else NoneType:comptime if present:return 42 # an `Int` converts to the return typeelse:return None -
The error for converting a function to an invalid function type now explains why the conversion cannot be made, such as a mismatch in argument counts, argument conventions, effects, etc:
def takes_read(f: def(Int) thin -> None):passdef mut_arg(mut x: Int):pass# error: ... cannot be converted from 'def mut_arg(mut x: Int) thin -> None'# to 'def(Int) thin -> None', argument 'x': expected 'imm' convention,# found 'mut'takes_read(mut_arg)
Language changes
-
@explicit_destroy("<message>")on a struct is deprecated and now emits a warning. Give the message on the struct'sDeinitableconformance instead:# Before@explicit_destroy("call `close()` instead")struct File(not Deinitable):...@explicit_destroy("use `deinit_with()` for non-Deinitable elements")struct Box[T: Movable](Deinitable where conforms_to(T, Deinitable)):...# Afterstruct File(not Deinitable else "call `close()` instead"):...struct Box[T: Movable](Deinitable where conforms_to(T, Deinitable) else ("use `deinit_with()` for non-Deinitable elements"),):...The message on a conditional
Deinitable where <condition> else "<message>"conformance is now reported when a value is abandoned for parameters that don't satisfy the condition. Previously, only an always-false conformance's message was reported. -
@explicit_destroy("<message>")on a trait is deprecated and now emits a warning. Only structs support a custom linear type error message. -
Precompiled packages now no longer leak names and provide the same surface as the same packages compiled from source. This may break your code (especially from
std):from std.os import rmdirdef main():std.os.rmdir(...) # This no longer works - use rmdir, or import std.os. -
It is now possible to
importa precompiled (.mojoc) package from a namespace, assuming it has been precompiled to be built at that namespace. See the help formojo precompile --namespacefor more information.
Library stabilizations
ImmSpanaliasMutSpanaliasList.insertList.clearSpan.__getitem__(self, slice: ContiguousSlice) -> Self:Span.__init__(out self, ref[Self.origin] list: List[Self.T]):Span.__init__(out self, ref[Self.origin, Self.address_space] array: Array[Self.T, _]):Span.__len__(self) -> Int:HashableHashable.__hash__
HasherHasher.updateHasher.finish
Pointer.__init__(to=)Pointer.__eq__Pointer.__ne__Pointer.unsafe_bitcast
Library performance improvements
-
Reduced the size of
Optional[T]to the size ofTwhenTis one of the following types, so code that stores them in anOptionaluses less memory:AllocationLayoutListManagedAllocationSpanStringStringSpanThinAllocation
Don't depend on this size. It relies on bit patterns that each type's current representation never uses, and that representation could change in the future.
Library changes
-
The following enum-like types now use
snake_casemember names. The uppercase names remain as deprecated aliases:Ordering:not_atomic,unordered,relaxed,acquire,release,acquire_release, andsequential.FastMathFlag:none,nnan,ninf,nsz,arcp,contract,afn,reassoc, andfast. Match patterns,String(), andrepr()use the new names too, so a pattern such ascase .CONTRACT:must becomecase .contract:.
-
An optional mutable pointer now implicitly converts to an optional immutable pointer, as
Pointerdoes. -
Added
normpath()tostd.os.path, matching Python'sos.path.normpath(). Contributed by @BlueDestination in #7342. -
Added
Path.devnull(), which returns the path to the platform's null device (/dev/nullon Linux and macOS), so code doesn't need to hardcode it. -
Added a builtin
filter(), which takes an iterable and a predicate closure and yields the elements the predicate accepts:filter(items, lambda (x: Int) -> Bool: x > 0). -
take_while()anddrop_while()instd.itertoolsnow take the predicate as an argument instead of a compile-time parameter, so it can be a closure that captures values. Writetake_while(items, pred)instead oftake_while[pred](items). -
List(length=, fill_with=)andArray(fill_with=)now accept a function that raises. If it raises, the initializer destroys the elements it already wrote and propagates the error. -
Span.binary_search_by()no longer takes the comparator as a compile-time parameter. Pass it as an argument,span.binary_search_by(cmp), which also lets it capture the value being searched for. -
QuickBench.run()instd.benchmarknow takes a single closure with no arguments in place of its eleven overloads for functions of 0 to 10 arguments. Capture the inputs instead of passing them separately:qb.run(lambda () {x} -> Float32: exp(x), bench_id=BenchId("exp")). -
ord()andCodepoint.ord()on a runtime string (StringSpan,String) now raise anErrorinstead of aborting when the string is empty. They also raise when the string holds more than one codepoint; previously they silently returned the first codepoint unless assertions were enabled. Callers must now handle the error withtryor araisesfunction. On a string literal, both never raise, and a literal that isn't exactly one codepoint is a compile-time error. Contributed by @Tharun-Kumar-McW in #7444.var text = String("🔥")var codepoint = ord(text) # 128293; raises if `text` isn't one codepointcomptime letter = ord("a") # 97; never raises -
pow()now takes a modulus as a third argument, like Python'spow():pow(base, exp, mod)computesbase ** exp % modfor integers of up to 64 bits without overflowing. The result has the sign ofmod, and a negativeexpuses the modular inverse ofbase, sopow(3, -1, 7)is5. -
Tupleelement types no longer need to beMovable. ATupleis nowMovableonly when all of its elements are.Tuplehas a newinit_withinitializer, which constructs each element in place from a closure parameterized on the element index:comptime T = Tuple[Pinned, Pinned] # `Pinned` is not `Movable`.var t = T(init_with=lambda [i: Int]() -> T.Ts[i]: Pinned(i * 10)) -
Layoutnow names its element countlength, matchingSpanandList. Construct one withLayout[T](length=n)and read the count back withlen(layout):LayoutandManagedAllocationnow conform toSized. TheLayout(count=)initializer and theLayout.count()method are deprecated.var allocation = alloc(Layout[Int32](length=4))for i in range(len(allocation)):allocation.unsafe_ptr().unsafe_offset(i).unsafe_write(Int32(i))dealloc(allocation^) -
Raising an integral
SIMDvalue (includingInt) or aSIMDLengthto a negative power now aborts at run time instead of silently returning0. Use a floating point base instead. -
Raising an
IntLiteralto a negativeIntLiteralpower now computes the exact result as a float literal, the reciprocal of the positive power, instead of evaluating to0. The result is a float literal even when the base is1or-1, sovar x = (-1)**-3is now aFloat64holding-1.0. Zero to a negative power evaluates tonan.var a = 2**-1 # 0.5, same as 1 / 2var b = Float64(2) ** -1 # 0.5var n = 2var c = n**-1 # aborts at run time -
Added
FileDescriptortostd.io, an owning wrapper aroundRawFileDescriptor. It is a linear type: close it explicitly withfd^.close(), which raises if the close fails. It is movable but not copyable, andOptional[FileDescriptor]is the size of a single descriptor.RawFileDescriptorgains a raisingclose()method.FileDescriptor(copy_borrowed=)duplicates a descriptor with close-on-exec set, so child processes don't inherit the copy. -
RawFileDescriptor.read_bytes(),RawFileDescriptor.fchdir(),RawFileDescriptor.close(),FileDescriptor.close(), andFileDescriptor(copy_borrowed=)now raiseIOError, so callers can match on the error'skind(). Code in a plainraisesfunction still compiles unchanged. -
File and directory functions in
std.os, such asmkdir(),remove(), andlistdir(), now raiseIOError, so you can check what went wrong withe.kind():try:os.remove(path)except e:if e.kind() != .not_found:raise e -
open(),FileHandle, and thePathmethods that read, write, or list files now raiseIOErrortoo.FileHandle.read()andPath.read_text()still raiseError, because decoding UTF-8 can fail. -
Added
BorrowedFileDescriptortostd.io, a copyable, non-owning view of aFileDescriptorthat carries the owner's origin, so it can be passed around without closing the descriptor or outliving its owner. -
ArcPointerelement types no longer need to beDeinitable. Destroy anArcPointerof a non-Deinitabletype with the newdeinit_with()method. -
Added an
OwnedPointer(init_with=)initializer that constructs the value in place, so the element type doesn't need to beMovable, and anOwnedPointer.deinit_with()method that destroys anOwnedPointerwhose element type isn'tDeinitable. The initializers that copied a value into the allocation are now deprecated. -
FileHandlenow owns its descriptor through aFileDescriptorand always refers to an open file. It is no longerDefaultable, andclose()consumes the handle (f^.close()) instead of leaving it in an invalid state. It still raises if the close fails. UseOptional[FileHandle], which is the same size asFileHandle, for a file that may not be open.NamedTemporaryFilefollows the same rules: it always holds an open file,close()consumes it, andOptional[NamedTemporaryFile]is the same size asNamedTemporaryFile. -
The
OptionalPointer,OptionalMutPointer, andOptionalImmPointeraliases are deprecated. WriteOptional[Pointer[T, origin]],Optional[MutPointer[T, origin]], orOptional[ImmPointer[T, origin]]instead. An_origin nested inside theOptionalmakes the function generic over it, as it did with the aliases:# Beforedef fill(buf: OptionalMutPointer[Byte, _]): ...# Afterdef fill(buf: Optional[MutPointer[Byte, _]]): ... -
The
StringSlice,ImmStringSpan, andImmStringSlicealiases are deprecated. UseStringSpaninstead.StringSpanis always immutable, so theImmvariants are redundant. -
Spannow conforms toEquatablewhen its element type does. -
stdin,stdout, andstderrare nowBorrowedFileDescriptorvalues, and thefileargument ofprint()takes aBorrowedFileDescriptorinstead of aRawFileDescriptor. You can pass aFileHandleorFileDescriptordirectly, since both convert implicitly:with open("log.txt", "w") as f:print("hello", file=f) -
SIMD.try_cast()converts between integer types, raisingTryCastSIMDErrorif any element is out of range.SIMD.cast()wraps instead, soInt(-1).cast[.uint8]()is 255.var byte = Int(255).try_cast[.uint8]() # 255var checked = Int(-1).try_cast[.uint8]() # raises TryCastSIMDErrorvar lanes = SIMD[.int32, 4](1, 2, 3, 300).try_cast[.uint8]() # raises -
find()andrfind()onString,StringSpan, andStringLiteralnow returnOptional[Int], holdingNonewhen the substring isn't found, instead of-1. Usex in sto test for a substring, or bind the offset with a pattern:var line = String("key=value")if case .Some(eq) = line.find("="):print(line[byte=:eq]) # keyprint("!" in line) # FalseOrdered checks such as
s.find(x) >= 0and arithmetic on the result no longer compile. Two old patterns still compile but now give the wrong answer, with no error or warning, so search your code for them:s.find(x) == -1is alwaysFalseands.find(x) != -1is alwaysTrue, because-1converts implicitly toOptional[Int]. This also applies when you store the result in a variable and compare it later.if s.find(x):is nowTrueonly whenxis found. Before, it wasTruewhenxwas missing andFalsewhenxwas at offset 0.
Interior origins
More standard library APIs now return references, pointers, spans, and
iterators that carry an interior origin of the value they point into,
instead of the value's own origin. Reassigning the value, or calling a
mut self method on it, invalidates them. Code that uses one afterward is now
a compile-time error; before, it compiled and read freed or destroyed memory.
These APIs now return interior origins:
List.unsafe_ptr().String.unsafe_ptr(),String.unsafe_ptr_mut(),as_c_string_span(),split_at_grapheme(), and theStringiterators, such ascodepoints()andbytes().Optional.value(),Optional.unsafe_value(), andOptional.__getitem__().OwnedPointer.ptr()andVariant.unsafe_get().- The pointers and spans that
Allocation,ManagedAllocation, andThinAllocationreturn.
Most code that no longer compiles matches one of these patterns:
-
A pointer held across a mutation, such as
append(), that can reallocate.var p = list.unsafe_ptr()list.append(4)print(p[]) # error: use of invalidated interior reference 'list["element"]' -
A reference used after its owner is reassigned.
ref i = opt.value()opt = Noneprint(i) # error: use of invalidated interior reference 'opt["value"]' -
A string mutated while one of its iterators is in use.
# error: use of invalidated interior reference 's["bytes"]'for c in s.codepoints():s += String(c)
GPU programming
-
Added the
apple-m6andapple-m6-metal4accelerator targets, andCompilationTarget.is_apple_m6()tostd.sys. Apple M6 GPUs are now detected automatically, so you no longer need to pass--target-accelerator=apple-m5on M6 hardware. -
compile_optionsnow reports an error for LLVM codegen flags such asframe-pointer=all, which it accepted before without effect. The only codegen flag that had an effect,denormal-fp-math-f32=<mode>, still sets the f32 denormal mode of NVIDIA GPU kernels, and other targets now reject it. -
Bool,Scalar(includingInt),String,StringSpan, andStringLiteralnow conform toConvertibleToPython, so they can be passed to generic code bounded on that trait. The dedicatedPythonObjectconstructors for these types are removed; implicit conversion still works through the singleConvertibleToPythonconstructor.ConvertibleToPythongains an associatedConversionToPythonErrorType(defaultNever), so conversions that cannot fail, such asBoolandScalar, stay non-raising, whileStringconversions keep raisingError. This is a breaking change. If a conversion is non-raising, theraiseseffect can be removed from theConvertibleToPythonconstructor. If a conversion is raising, an error type must be assigned toConversionToPythonErrorType. Contributed by @christoph-schlumpf in #6547.
Tooling changes
-
mojo buildandmojo runcan now report what elaboration produced, to show which compile-time code makes a compile slow.--elaboration-statslists eachcomptime forloop with its iteration count and the operations its unrolled iterations produced. It also lists the calls that compile-time evaluation made to the interpreter, summed by function and by call site, with their cache hits and the CPU time spent interpreting. The report has one part for each pipeline that elaborated: the host and each accelerator target. This option is hidden; use--help-hiddento list it.Like the timing reports, the report prints as text to stderr by default.
--timing-jsonprints it as JSON instead, under anelaborationkey, and--timing-filewrites it to a file instead of stderr. If the compilation hits the cache, elaboration is skipped and nothing is reported. Clear compilation cache or pointMODULAR_CACHE_DIRat an empty directory to get a full report. -
mojo buildandmojo runhave a new hidden--parser-statsoption that reports the time the parser spends to resolve each declaration, to show which declarations make parsing slow. Each declaration's time excludes the resolutions it caused, so the times add up to the total parse time. The report uses the same output options as--elaboration-stats. -
mojo precompilemay now take a--namespaceoption to allow it to bake the provided namespace into the package. A packagepkgbuilt with--namespace foo.barmust be placed atfoo/bar/pkg.mojocand imported asfoo.bar.pkg. While precompiling, the package may refer to itself both bypkgand byfoo.bar.pkg. Both paths resolve to the source being compiled.
Removed
-
Legacy closures are removed. The
capturingfunction effect and the@__parameter(and@parameter),@__copy_capture, and@__move_capturedecorators are now errors. Declare a nested function's captures in a capture list instead, and pass the closure as a value:def apply[F: def(Int) -> Int](f: F, x: Int) -> Int:return f(x)def main():var offset = 10def add(x: Int) {var offset} -> Int: # was @__copy_capture(offset)return x + offsetprint(apply(add, 1))A function passed as a compile-time parameter must now be
thin, for example[f: def(Int) thin -> Int]. -
CompiledFunctionInfono longer hasnum_captures,capture_sizes, orpopulatemembers. Kernels can no longer capture implicitly, so these were always empty. -
The AMD-only intrinsics
readfirstlane(),sendmsg(), andimplicitarg_ptr()moved fromstd.sys.intrinsicstomax.gpu.intrinsics, next to the other vendor-specific GPU intrinsics. Import them from there instead.std.sys.intrinsics.ballot()is removed; usemax.gpu.primitives.warp.vote(), which works on every GPU vendor. -
The
PowableandCeilDivableRaisingtraits are removed. A type that defines__pow__()still supports the**operator without conforming to a trait, andpow()now takesSIMDvalues only. Nothing conformed toCeilDivableRaising, so the raisingceildiv()overload is removed too. -
Removed APIs that were deprecated in Mojo 1.1 or earlier. Use the replacement in each case:
-
The
UnsafePointeralias and thestd.memory.unsafe_pointermodule that defined it. UsePointer. -
The
Pointermethodsload(),store(),strided_load(),strided_store(),gather(),scatter(),free(),bitcast(),address_space_cast(), andtake_pointee(). Use theirunsafe_-prefixed spellings, such asunsafe_load(). -
Pointer.mut_cast(). Spell the mutability in the pointer type (ImmPointerorMutPointer), or useunsafe_mut_cast(). -
Subtracting an integer from a
Pointerand the+=and-=operators. Useunsafe_offset(). Adding an integer and positional indexing such asptr[i]remain deprecated. -
memmove(). Useunsafe_memmove(). -
The
alloc[T](count)overload. Usealloc(Layout[T](length=count)), which returns anAllocation, orunsafe_alloc[T](count)for a raw pointer. -
is_trivially_movable(),is_trivially_copyable(), andis_trivially_deletable(). UseIsTriviallyMovable[T],IsTriviallyCopyable[T], andIsTriviallyDeinitable[T]fromstd.traits. -
The
CStringSlicealias andas_c_string_slice()onString,StringSlice, andStringLiteral. UseCStringSpanandas_c_string_span(). -
unsafe_ptr()onArcPointer,OwnedPointer,CStringSpan, andStringLiteral. Useptr(). -
String.capacity()andString.reserve(). Usecapacity_bytes()andreserve_bytes(). -
Tuple.element_typesandVariadicPack.element_types. UseTs. -
The
AnyTypeandDeinitablealiases instd.builtin.anytype, and theMovable,Copyable, andImplicitlyCopyablealiases instd.builtin.value. These traits live instd.traitsand are still exported from the prelude.
-
Fixed
-
VariadicPacknow conforms toWritablewhen all of its element types do, so a pack can be passed toprint(),String()andrepr(). -
find()andrfind()onString,StringSpanandStringLiteralnow honorstartwhen the substring is empty."abc".find("", 2)returns2instead of0, and both methods returnNonewhenstartis past the end of the string. Contributed by @dhruvilmehta in #7451 and @Antony-mcw in #7668. -
A bare
raisein anexceptblock no longer crashes the compiler when building with debug info. -
std.ffi.c_pid_tis nowc_intinstead ofInt, matching the 32-bit Cpid_ton Linux and macOS. As anInt, a-1returned by a function such aswaitpid()read back as a large positive number, so checks for-1or a negative result never fired. -
On Apple GPUs, building a
SIMDfrom device-buffer elements in a kernel, as inSIMD[DType.float32, 2](src[i], src[i]), no longer reads zeros. -
SIMD.slice()no longer passesllvm.vector.extractan offset that is not a multiple of the output width, which LLVM rejects. A wide slice at such an offset, likeslice[16, offset=8]()on a 32-element vector, now takes the element-wise path, and aligned slices narrower than the target's native vector width, such as the halvessplit()returns for small vectors, now use the intrinsic. -
**with an integer exponent no longer truncates the exponent to 32 bits, soFloat64(2.0) ** Int64(4294967296)is nowinfinstead of1.0, andFloat64(2.0) ** Int32.MINis now0.0instead of1.0. -
Fixed rejection of negative integer and floating-point literals in
matchpatterns. Contributed by @a-tarasyuk in #7316. -
A
comptime if conforms_to(T, Deinitable)guard now correctly refinesTand deinits it after its last use. -
Building a
SIMDvalue from a list literal with the wrong number of elements is now a compile-time error. Previously,var x: Int = [1, 2, 3, 4]compiled and kept only the first element. -
Printing a
Float32orFloat64now produces the shortest decimal that rounds back to the same value, with ties rounded to even. Previously about oneFloat32in 200 printed a decimal that parsed back to a neighboring value (for example,33560532.0printed as33560530.0), and values exactly halfway between two shortest decimals, such as3.37890625, rounded up instead of to even. -
atol()now rejects a number that ends in an underscore when whitespace follows it, as it already did without the whitespace. Previouslyatol("9_ ")returned90. -
Process.run()now passes the child process the arguments it was given. Arguments built at run time, such asString("a") + String(i), reached the child as repeated copies of the last argument or as freed memory. -
Fixed a bug where a function that modified the elements of a
mutvariadic pack (mut *args: *Ts), or of aVariadicPackwith mutable elements, could leave the values passed to it unchanged. -
input()no longer raisesEOFafter the first line when stdin is a pipe or redirected file. -
std.sys.exit()is now declared-> Never, so a function with a return type can end in a call toexit()without a trailingreturn. -
#7339 - Mojo now keeps compilation caches that another installed Mojo or MAX still uses. MAX, the
mojoCLI and projects on different Mojo versions can now share one cache directory. A process can still lose its cache if its Mojo install is replaced while it runs. -
Dict,StringDict,Deque,LinkedListandList.insert()now accept elements whose type names a mutable origin, such asPointer[Int, origin_of(x)], asList.append()already did. Inserting one was rejected as aliasing the collection. -
FileHandlecan now read and write more than 2 GiB at once on macOS, instead of raisingInvalid argumentor aborting. -
#7669 - At compile time,
unsafe_memmove()is fixed.List.insert()evaluated at compile time no longer repeats the element at the insertion point, andList.insert()andList.pop(i)now work on lists such asList[String]. -
A NUL byte (
\0) in the literal text of a t-string is now kept as text. Previously it ended the literal segment early, sot"a\0b{x}"withx = "ls"producedalsbinstead ofa\0bls.