Move the engine core into core/, a project of its own (pplus-core)

What programs mean (the languages, translators, Mojo checker and
interpreter, prover, fuzzer, machine model, catalog problems and the Mojo
corpus with godbolt's stored answers) was mixed into the site's tree, so a
change to the prover and a change to a button went through the same gate
and the same docs. This moves all of it under core/, laid out as its own
repository, ready to be extracted with its history and pinned here as a
git submodule.

- core/: src/{engines,services,sync,mojo,exercises,curriculum,common},
  mojo/, syntax/mojo.xml, its tests (with Workspace and workForProblem in
  place of the site's Session), scripts (corpus pipeline, play, the
  exercise and probe starters, engines export/diff), and its docs
  (engines, trust, mojo-corpus, exercises, coverage). Its own pixi.toml,
  package.json, README, AGENTS.md and CI workflow.
- core/tests/boundary.test.mjs: library modules use no DOM, import no
  page widget, and import nothing outside src/.
- core/scripts/cli.mjs: pixi run cli check|run|prove|fuzz|translate.
- core/scripts/dafny.py: Dafny 4.11.0 pinned by version and SHA-256 per
  platform, fetched into .tools/ (pixi run dafny-fetch, pixi run dafny).
- The site imports core only as #core/<path>.js: an import map in
  index.html, "imports" in package.json for node, core's declarations for
  tsc. The site's TypeScript builds core first (npm run build).
- assemble.sh, the Quarto engine copy, the render cache key, check-pages,
  quarto-export and quarto-css read core/dist and core/mojo; quarto-css
  copies core's syntax/mojo.xml into the extension.
- Site tests that covered engines moved to core; the rest keep Session.
- README, AGENTS.md, docs/app.md, docs/deploy.md and the CI workflow
  describe the split (checkout with submodules; core's tests and corpus
  status run against the pinned commit).

Gate: site 110 pass; core 307 pass; corpus status --strict passes.
Manual check: the assembled site opens Bridge (count-base-proved),
Developer and Hardware (count-base) with the editor, the stepper and the
board, and no module errors.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FgvbRdoEheAHqsRmr2WuKZ
This commit is contained in:
alexmandClaude committed 2026-10-05 05:43:58 +00:00
1 parent f43bbfe0cf
commit 82e18f7966
1567 files changed
+3670 -981

No files matched your search

@@ -0,0 +1,57 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
# start-loop
def loop():
for x in range(5):
if x % 2 == 0:
print(x)
# end-loop
def matrix_multiply(a: Int, b: Int, c: Int):
pass
# fmt: off
def linebreaks():
var matrix_a = 10
var matrix_b = 20
var result_matrix = 5
# start-linebreaks-in-function
matrix_multiply(
matrix_a,
matrix_b,
result_matrix
)
# end-linebreaks-in-function
# fmt: on
def linebreaks2():
# start-multiline-string
var long_text = (
"This is a long line of text that is a lot easier to read if"
" it is broken up across two lines instead of one long line."
)
# end-multiline-string
_ = long_text
def main():
loop()
linebreaks()
linebreaks2()
@@ -0,0 +1,26 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
# This is a comment. The Mojo compiler ignores this line.
def trailing_comment():
# start-trailing-comment
var message = "Hello, World!" # This is also a valid comment
# end-trailing-comment
_ = message
def main():
trailing_comment()
@@ -0,0 +1,27 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
# start-docstring
def print(x: String):
"""Prints a string.
Args:
x: The string to print.
"""
...
# end-docstring
def main():
print(String("Hello, world!"))
@@ -0,0 +1,29 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
def explicit_variable():
# start-explicit-variable
var x = 10
# end-explicit-variable
_ = x
# start-typed-variables
def main():
var x: Int = 10
var sum: Int
sum = x + x
# end-typed-variables
_ = sum
explicit_variable()
@@ -0,0 +1,22 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
# start-greet
def greet(name: String) -> String:
return "Hello, " + name + "!"
# end-greet
def main():
print(greet("Mojo"))
@@ -0,0 +1,18 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
# start-hello-world
def main():
print("Hello, world!")
# end-hello-world
@@ -0,0 +1,31 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
# start-parametric-function
def repeat[count: Int](msg: String):
# evaluate the following for loop at compile time
comptime for i in range(count):
print(msg)
# end-parametric-function
# start-call-parametric-function
def call_repeat():
repeat[3]("Hello")
# Prints "Hello" 3 times
# end-call-parametric-function
def main():
call_repeat()
@@ -0,0 +1,24 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
# start-python-integration
from std.python import Python
def main() raises:
var np = Python.import_module("numpy")
var ar = np.arange(15).reshape(3, 5)
print(ar)
print(ar.shape)
# end-python-integration
@@ -0,0 +1,41 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
# start-mypair
struct MyPair(Copyable):
var first: Int
var second: Int
def __init__(out self, first: Int, second: Int):
self.first = first
self.second = second
def __init__(out self, *, copy: Self):
self.first = copy.first
self.second = copy.second
def dump(self):
print(self.first, self.second)
# end-mypair
# start-use-mypair
def use_mypair():
var mine = MyPair(2, 4)
mine.dump()
# end-use-mypair
def main():
use_mypair()
@@ -0,0 +1,28 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
# start-mypair-fieldwise
@fieldwise_init
struct MyPair(Copyable):
var first: Int
var second: Int
def dump(self):
print(self.first, self.second)
# end-mypair-fieldwise
def main():
var mine = MyPair(2, 4)
mine.dump()
@@ -0,0 +1,51 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
# start-trait
trait SomeTrait:
def required_method(self, x: Int):
...
# end-trait
# start-conforming-struct
@fieldwise_init
struct SomeStruct(SomeTrait):
def required_method(self, x: Int):
print("hello traits", x)
# end-conforming-struct
# start-generic-function
def fun_with_traits[T: SomeTrait](x: T):
x.required_method(42)
def use_trait_function():
var thing = SomeStruct()
fun_with_traits(thing)
# end-generic-function
def typed_collection():
# start-typed-collection
var my_list = List[Float64]()
# end-typed-collection
_ = my_list
def main():
use_trait_function()
typed_collection()
@@ -0,0 +1,63 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
# test_c_number_types.mojo
# Tests for c-ffi.mdx: "C number types" table.
#
# Verifies the std.ffi C type aliases have the widths the table documents.
from std.ffi import (
c_char,
c_double,
c_float,
c_int,
c_long,
c_long_long,
c_short,
c_size_t,
c_ssize_t,
c_uchar,
c_uint,
c_ulong,
c_ushort,
)
from std.sys import size_of
from std.testing import assert_equal
# --- Fixed-width aliases ---
def test_fixed_width_aliases() raises:
assert_equal(size_of[c_char](), 1)
assert_equal(size_of[c_uchar](), 1)
assert_equal(size_of[c_short](), 2)
assert_equal(size_of[c_ushort](), 2)
assert_equal(size_of[c_int](), 4)
assert_equal(size_of[c_uint](), 4)
assert_equal(size_of[c_long_long](), 8)
assert_equal(size_of[c_float](), 4)
assert_equal(size_of[c_double](), 8)
# --- Pointer-width aliases (64-bit Linux and macOS targets) ---
def test_pointer_width_aliases() raises:
assert_equal(size_of[c_long](), 8)
assert_equal(size_of[c_ulong](), 8)
assert_equal(size_of[c_size_t](), 8)
assert_equal(size_of[c_ssize_t](), 8)
def main() raises:
test_fixed_width_aliases()
test_pointer_width_aliases()
@@ -0,0 +1,117 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
# test_call_libc.mojo
# Tests for c-ffi.mdx: "Call libc functions", including the clock_gettime
# struct-by-pointer example and the div struct-by-value example.
from std.ffi import (
OwnedDLHandle,
c_char,
c_int,
c_long,
c_size_t,
external_call,
)
from std.sys.info import platform_map
from std.testing import assert_equal, assert_true
# --- external_call: rand ---
def random_int() -> c_int:
return external_call["rand", c_int]()
def test_rand() raises:
# rand() returns a non-negative int; 1 + (r % 10) lands in [1, 10].
var raw = random_int()
assert_true(raw >= 0)
var bounded = 1 + raw % 10
assert_true(bounded >= 1)
assert_true(bounded <= 10)
# --- external_call: struct passed by pointer (clock_gettime) ---
@fieldwise_init
struct CTimeSpec(RegisterPassable): # Matches C's struct timespec.
# CLOCK_MONOTONIC differs by platform
comptime monotonic = c_int(
platform_map["CLOCK_MONOTONIC", linux=1, macos=6]()
)
var tv_sec: c_long
var tv_nsec: c_long
@staticmethod
def monotonic_nanos() raises -> c_long:
var time_spec = Self(0, 0)
if (
external_call["clock_gettime", c_int](
Self.monotonic,
Pointer(to=time_spec),
)
!= 0
):
raise Error("clock_gettime failed")
return time_spec.tv_sec * 1_000_000_000 + time_spec.tv_nsec
def test_clock_gettime() raises:
var first = CTimeSpec.monotonic_nanos()
assert_true(first > 0)
var second = CTimeSpec.monotonic_nanos()
assert_true(second >= first) # monotonic clock never goes backward
# --- get_function: struct returned by value (div) ---
@fieldwise_init
struct DivT(RegisterPassable): # Mirrors C div_t: two ints, 8 bytes.
var quot: c_int
var rem: c_int
def test_div_struct_by_value() raises:
var proc = OwnedDLHandle() # no path: opens the current process
var div = proc.get_function[DivT]("div")
var d = div(c_int(7), c_int(3))
assert_equal(d.quot, c_int(2))
assert_equal(d.rem, c_int(1))
# --- external_call: variadic callee needs num_fixed_args (snprintf) ---
def test_snprintf_variadic() raises:
var buf = Array[c_char, 64](uninitialized=True)
var written = external_call["snprintf", c_int, num_fixed_args=3](
buf.unsafe_ptr(),
c_size_t(64),
"score: %d/%d".as_c_string_span(),
c_int(7),
c_int(10),
)
assert_equal(written, c_int(11))
assert_equal(
String(unsafe_from_utf8_ptr=buf.unsafe_ptr()), String("score: 7/10")
)
def main() raises:
test_rand()
test_clock_gettime()
test_div_struct_by_value()
test_snprintf_variadic()
@@ -0,0 +1,120 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
# test_memory.mojo
# Tests for c-ffi.mdx: "Memory management", covering malloc with an Optional
# return, the CBuffer context manager, null handling with getenv, and
# origins keeping Mojo memory alive.
from std.ffi import OwnedDLHandle, c_char, c_int, c_size_t, external_call
from std.testing import assert_equal, assert_true
# --- Allocate C memory with malloc, then free it ---
def create_buffer(
n: c_size_t,
) -> Optional[Pointer[UInt8, MutUntrackedOrigin]]:
return external_call[
"malloc", Optional[Pointer[UInt8, MutUntrackedOrigin]]
](n)
def test_malloc_free() raises:
var allocated = create_buffer(c_size_t(16))
assert_true(Bool(allocated), "malloc failed")
var buf = allocated.value()
buf[unsafe_offset=0] = 42
buf[unsafe_offset=1] = 7
assert_equal(buf[unsafe_offset=0], UInt8(42))
assert_equal(buf[unsafe_offset=1], UInt8(7))
external_call["free", NoneType](buf.unsafe_bitcast[NoneType]())
# --- Context manager that frees C memory automatically ---
struct CBuffer:
var ptr: Pointer[UInt8, MutUntrackedOrigin]
var size: c_size_t
def __init__(out self, n: c_size_t) raises:
self.size = n
var allocated = external_call[
"malloc", Optional[Pointer[UInt8, MutUntrackedOrigin]]
](n)
if not allocated:
raise Error("malloc failed")
self.ptr = allocated.value()
def __enter__(self) -> Pointer[UInt8, MutUntrackedOrigin]:
return self.ptr
def __exit__(self):
external_call["free", NoneType](self.ptr.unsafe_bitcast[NoneType]())
def test_context_manager() raises:
with CBuffer(c_size_t(1024)) as buf:
buf[unsafe_offset=0] = 42
assert_equal(buf[unsafe_offset=0], UInt8(42))
# --- Null-able C pointer wrapped in Optional (getenv) ---
def test_getenv_optional() raises:
# Set our own variable so the test doesn't depend on the ambient
# environment (a bazel sandbox may strip PATH).
var key: String = "MOJO_FFI_TEST_VAR"
var value: String = "present"
_ = external_call["setenv", c_int](
key.as_c_string_span(),
value.as_c_string_span(),
c_int(1), # overwrite
)
var wrapped = external_call[
"getenv", Optional[Pointer[c_char, MutUntrackedOrigin]]
](key.as_c_string_span())
assert_true(Bool(wrapped))
assert_equal(
String(unsafe_from_utf8_ptr=wrapped.value()), String("present")
)
var missing: String = "MOJO_FFI_DEFINITELY_NOT_SET_98765"
var empty = external_call[
"getenv", Optional[Pointer[c_char, MutUntrackedOrigin]]
](missing.as_c_string_span())
assert_true(not empty)
# --- Origins keep Mojo memory alive across a C call ---
def test_origin_keeps_alive() raises:
var proc = OwnedDLHandle() # No path: opens the current process.
var c_strlen = proc.get_function[c_size_t]("strlen")
var line = String("Hello")
assert_equal(Int(c_strlen(line.as_c_string_span())), 5)
# Refill the same variable; the pointer's origin still holds.
line = "Hello, Mojo!"
assert_equal(Int(c_strlen(line.as_c_string_span())), 12)
def main() raises:
test_malloc_free()
test_context_manager()
test_getenv_optional()
test_origin_keeps_alive()
@@ -0,0 +1,111 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
# test_pointers.mojo
# Tests for c-ffi.mdx: "Passing pointers", the frexp out-parameter example,
# the qsort opaque-pointer + callback example, and the getcwd Array/Span
# example.
from std.ffi import c_char, c_double, c_int, c_size_t, external_call
from std.sys import size_of
from std.testing import assert_equal, assert_true
# --- bitcast a typed pointer to an opaque void* ---
def test_opaque_pointer() raises:
var value: c_int = 42
var p = Pointer(to=value) # Pointer to a C int
var opaque: OpaquePointer[origin_of(value)] = p.unsafe_bitcast[NoneType]()
# Reinterpreting the pointer doesn't change the address it holds.
assert_equal(Int(opaque), Int(p))
_ = value
# --- typed pointer as a C out-parameter (frexp) ---
def test_frexp_out_parameter() raises:
var exponent: c_int = 0
var mantissa = external_call["frexp", c_double](
c_double(12.0), Pointer(to=exponent)
)
# 12.0 == 0.75 * 2**4, so C wrote 4 through the pointer.
assert_equal(mantissa, c_double(0.75))
assert_equal(exponent, c_int(4))
# --- opaque pointers plus a callback (qsort) ---
def compare(
a: OpaquePointer[mut=False, _],
b: OpaquePointer[mut=False, _],
) abi("C") -> c_int:
var a_value = a.unsafe_bitcast[c_int]()[]
var b_value = b.unsafe_bitcast[c_int]()[]
# `qsort` only needs to know which value is larger. Compare the values
# instead of subtracting them. Large differences can overflow, producing
# the wrong comparison result and sorting the values incorrectly.
if a_value < b_value:
return c_int(-1)
return c_int(a_value > b_value)
def test_qsort() raises:
# The two extremes are far enough apart that a subtracting comparator
# overflows `c_int` and strands them at the front, so this fixture fails
# against the `a - b` form the example used to show.
var numbers: List[c_int] = [5, 2_000_000_000, 9, -2_000_000_000, 1, 5]
external_call["qsort", NoneType](
numbers.unsafe_ptr(),
c_size_t(len(numbers)),
c_size_t(size_of[c_int]()),
compare,
)
var expected: List[c_int] = [-2_000_000_000, 1, 5, 5, 9, 2_000_000_000]
for i in range(len(numbers)):
assert_equal(numbers[i], expected[i])
# --- C fills a Mojo-owned Array, then a Span wraps the result (getcwd) ---
def test_getcwd_array_span() raises:
comptime CAPACITY = 256
var buf = Array[c_char, CAPACITY](uninitialized=True)
var filled = external_call[
"getcwd", Optional[Pointer[c_char, origin_of(buf)]]
](buf.unsafe_ptr(), c_size_t(CAPACITY))
assert_true(Bool(filled), "getcwd failed")
var length = external_call["strlen", c_size_t](buf.unsafe_ptr())
var span = Span(
unsafe_ptr=buf.unsafe_ptr().unsafe_bitcast[Byte](), length=Int(length)
)
# Asserting the real path would tie the test to the machine, so check
# invariants instead.
assert_true(len(span) > 0)
# `strlen` stops before C's terminator, so the byte past the span is nul.
# This is what ties the span's length to C's idea of where the data ends.
assert_equal(buf[Int(length)], c_char(0))
var cwd = String(from_utf8=span)
assert_equal(len(cwd.as_bytes()), Int(length))
assert_equal(cwd.as_bytes()[0], Byte(ord("/")))
def main() raises:
test_opaque_pointer()
test_frexp_out_parameter()
test_qsort()
test_getcwd_array_span()
@@ -0,0 +1,36 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
# test_shared_libraries.mojo
# Tests for c-ffi.mdx: "Use shared libraries" and "Retrieve functions by name".
#
# Not tested at runtime (intentional):
# - The libncursesw and libcurl examples load libraries that aren't
# guaranteed present in the test environment. This test exercises the
# same OwnedDLHandle + get_function path against a guaranteed libc
# symbol (abs), which stands in for those examples.
from std.ffi import OwnedDLHandle, c_int
from std.testing import assert_equal
# --- get_function, parameterized on the C return type ---
def test_get_function() raises:
var proc = OwnedDLHandle() # no path: opens the current process
var c_abs = proc.get_function[c_int]("abs")
assert_equal(c_abs(c_int(-5)), c_int(5))
assert_equal(c_abs(c_int(5)), c_int(5))
def main() raises:
test_get_function()
@@ -0,0 +1,52 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
# test_string_lifetime.mojo
# Tests for c-ffi.mdx: keeping a Mojo string alive across a C call, and
# reusing one buffer across repeated calls while its origin stays valid.
from std.ffi import OwnedDLHandle, c_char, c_size_t, external_call
from std.testing import assert_equal
# --- Keep a string alive for the duration of the C call ---
def test_keep_alive() raises:
var s = String("x")
var length = external_call["strlen", c_size_t](s.as_c_string_span())
assert_equal(Int(length), 1)
_ = s # manual last use keeps `s` alive until here
# --- Pin the parameter's origin to a string, refill across calls ---
def test_origin_pinned_refill() raises:
var proc = OwnedDLHandle() # no path: opens the current process
var line = String("Hello")
var c_strlen = proc.get_function[c_size_t]("strlen")
# The pointer carries `line`'s origin, so `line` stays alive across
# the call without a manual keep-alive.
var length = c_strlen(line.as_c_string_span())
assert_equal(Int(length), 5)
# Refill the same buffer; the origin stays valid.
line = "Hello, Mojo!"
length = c_strlen(line.as_c_string_span())
assert_equal(Int(length), 12)
def main() raises:
test_keep_alive()
test_origin_pinned_refill()
@@ -0,0 +1,73 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
# test_strings.mojo
# Tests for c-ffi.mdx: "Passing strings", covering Mojo->C conversion,
# C->Mojo conversion via strdup + Span, and string literals as C strings.
from std.ffi import c_char, c_int, c_size_t, external_call
from std.testing import assert_equal, assert_true
# --- Mojo String -> C char* (verified by measuring it with strlen) ---
def test_mojo_string_to_c() raises:
var name: String = "hello"
var length = external_call["strlen", c_size_t](name.as_c_string_span())
assert_equal(Int(length), 5)
_ = name
# --- Mojo String -> C char* consumed by a real C function (atoi) ---
def test_atoi() raises:
var value: String = "42" # Well-formed ASCII number
var s_ptr = value.as_c_string_span().ptr() # null-terminated char*
var result: c_int = external_call["atoi", c_int](s_ptr)
assert_equal(result, c_int(42))
_ = value
# --- C char* -> Mojo String via strdup + Span ---
def test_c_string_to_mojo() raises:
var name: String = "Echo"
var cptr = external_call[
"strdup", Optional[Pointer[c_char, MutUntrackedOrigin]]
](name.as_c_string_span().ptr())
assert_true(Bool(cptr))
var ptr = cptr.value()
# Measure the C buffer with strlen, not the Mojo string's byte_length.
var length = external_call["strlen", c_size_t](ptr)
var span = Span(unsafe_ptr=ptr.unsafe_bitcast[Byte](), length=Int(length))
assert_equal(String(from_utf8=span), String("Echo"))
external_call["free", NoneType](ptr.unsafe_bitcast[NoneType]())
_ = name
# --- String literal -> C string (verified by measuring it with strlen) ---
def test_literal_to_c() raises:
var length = external_call["strlen", c_size_t](
"libm.so.6".as_c_string_span().ptr()
)
assert_equal(Int(length), 9) # "libm.so.6" is 9 bytes
def main() raises:
test_mojo_string_to_c()
test_atoi()
test_c_string_to_mojo()
test_literal_to_c()
@@ -0,0 +1,26 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
def main():
# Conditional expression
var temp_celsius = 15
var forecast = "warm" if temp_celsius > 20 else "cool"
print("The forecast for today is", forecast)
# Equivalent if-else statement
if temp_celsius > 20:
forecast = "warm"
else:
forecast = "cool"
print("The forecast for today is", forecast)
@@ -0,0 +1,95 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
from std.python import Python
def main() raises:
var states: List = [String("California"), "Hawaii", "Oregon"]
for state in states:
print(state)
var numbers = {42, 0}
for number in numbers:
print(number)
var capitals: Dict[String, String] = {
"California": "Sacramento",
"Hawaii": "Honolulu",
"Oregon": "Salem",
}
for var state in capitals:
print(t"{capitals[state]}, {state}")
for item in capitals.items():
print(t"{item.value}, {item.key}")
for i in range(5):
print(i, end=", ")
# Extra print statements added to separate the output of the different loops
print()
for i in range(5):
if i == 3:
continue
print(i, end=", ")
print()
for i in range(5):
if i == 3:
break
print(i, end=", ")
print()
for i in range(5):
print(i, end=", ")
else:
print("\nFinished executing 'for' loop")
print()
var empty = List[Int]()
for i in empty:
print(i)
else:
print("Finished executing 'for' loop")
var animals: List = ["cat", "aardvark", "hippopotamus", "dog"]
for animal in animals:
if animal == "dog":
print("Found a dog")
break
else:
print("No dog found")
# Using references to modify a list item in a loop
var values: List = [1, 4, 7, 3, 6, 11]
for ref value in values:
if value % 2 != 0:
value -= 1
print(values)
# from python import Python
# Iterate over a mixed-type Python dictionary
var py_dict = Python.evaluate("{'a': 1, 'b': 2.71828, 'c': 'sushi'}")
for py_key in py_dict: # Each key is of type "PythonObject"
print(py_key, py_dict[py_key])
# Iterate over a mixed-type Python dictionary using items()
py_dict = Python.evaluate("{'a': 1, 'b': 2.71828, 'c': 'sushi'}")
for py_tuple in py_dict.items(): # Each 2-tuple is of type "PythonObject"
print(py_tuple[0], py_tuple[1])
@@ -0,0 +1,38 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
def main():
# Simple if statement
var temp_celsius = Float64(25)
if temp_celsius > 20:
print("It is warm.")
print("The temperature is", temp_celsius * 9 / 5 + 32, "Fahrenheit.")
# Single-line if statements
temp_celsius = 22
# fmt: off
if temp_celsius < 15: print("It is cool.") # Skipped because condition is False
if temp_celsius > 20: print("It is warm.")
# fmt: on
# Else and elif statements
temp_celsius = 25
if temp_celsius <= 0:
print("It is freezing.")
elif temp_celsius < 20:
print("It is cool.")
elif temp_celsius < 30:
print("It is warm.")
else:
print("It is hot.")
@@ -0,0 +1,32 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
def main():
# Short-circuit "or" evaluation
def true_func() -> Bool:
print("Executing true_func")
return True
def false_func() -> Bool:
print("Executing false_func")
return False
print('Short-circuit "or" evaluation')
if true_func() or false_func():
print("True result")
# Short-circuit "and" evaluation
print('Short-circuit "and" evaluation')
if false_func() and true_func():
print("True result")
@@ -0,0 +1,65 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
def main():
# While loop
var fib_prev = 0
var fib_curr = 1
print(fib_prev, end="")
while fib_curr < 50:
print(",", fib_curr, end="")
fib_prev, fib_curr = fib_curr, fib_prev + fib_curr
print()
# While loop with continue statement
var n = 0
while n < 5:
n += 1
if n == 3:
continue
print(n, end=", ")
print()
# While loop with break statement
n = 0
while n < 5:
n += 1
if n == 3:
break
print(n, end=", ")
print()
# While loop with else statement
n = 5
while n < 4:
print(n)
n += 1
else:
print("Loop completed")
print()
# While loop with break and else statement
n = 0
while n < 5:
n += 1
if n == 3:
break
print(n)
else:
print("Executing else clause")
@@ -0,0 +1,69 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
import std.time
@fieldwise_init
struct ConditionalTimer(ImplicitlyCopyable):
var start_time: Int
def __init__(out self):
self.start_time = 0
def __enter__(mut self) -> Self:
self.start_time = std.time.perf_counter_ns()
return self
def __exit__(mut self):
var end_time = std.time.perf_counter_ns()
var elapsed_time_ms = round(
Float64(end_time - self.start_time) / 1e6, 3
)
print("Elapsed time:", elapsed_time_ms, "milliseconds")
def __exit__(mut self, e: Error) -> Bool:
if String(e) == "just a warning":
print("Suppressing error:", e)
self.__exit__()
return True
else:
print("Propagating error")
self.__exit__()
return False
def flaky_identity(n: Int) raises -> Int:
if (n % 4) == 0:
raise "really bad"
elif (n % 2) == 0:
raise "just a warning"
else:
return n
def main() raises:
for i in range(1, 9):
with ConditionalTimer():
print("\nBeginning execution")
print("i =", i)
std.time.sleep(0.1)
if i == 3:
print("continue executed")
continue
var j = flaky_identity(i)
print("j =", j)
print("Ending execution")
@@ -0,0 +1,43 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
import std.sys
import std.time
@fieldwise_init
struct Timer(ImplicitlyCopyable):
var start_time: Int
def __init__(out self):
self.start_time = 0
def __enter__(mut self) -> Self:
self.start_time = std.time.perf_counter_ns()
return self
def __exit__(mut self):
var end_time = std.time.perf_counter_ns()
var elapsed_time_ms = round(
Float64(end_time - self.start_time) / 1e6, 3
)
print("Elapsed time:", elapsed_time_ms, "milliseconds")
def main() raises:
with Timer():
print("Beginning execution")
std.time.sleep(1.0)
if len(std.sys.argv()) > 1:
raise "simulated error"
std.time.sleep(1.0)
print("Ending execution")
@@ -0,0 +1,70 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
@fieldwise_init
struct FileError(Equatable, ImplicitlyCopyable, Writable):
var _variant: Int
# Compile-time constant variants
comptime not_found = FileError(_variant=1)
comptime permission_denied = FileError(_variant=2)
comptime already_exists = FileError(_variant=3)
def variant_name(self) -> String:
if self._variant == 1:
return "not_found"
elif self._variant == 2:
return "permission_denied"
elif self._variant == 3:
return "already_exists"
return "unknown"
def write_to(self, mut writer: Some[Writer]):
writer.write("FileError.", self.variant_name())
def open_file(path: String) raises FileError -> String:
if not path:
raise FileError.not_found
if path == "/secret":
raise FileError.permission_denied
if path == "/existing":
raise FileError.already_exists
return "Contents of " + path
def handle_file_error(e: FileError):
if e == FileError.not_found:
print("Not found:", e)
elif e == FileError.permission_denied:
print("Permission denied:", e)
elif e == FileError.already_exists:
print("Already exists:", e)
def main():
try:
print(open_file("/data"))
except e:
handle_file_error(e)
try:
print(open_file(""))
except e:
handle_file_error(e)
try:
print(open_file("/secret"))
except e:
handle_file_error(e)
@@ -0,0 +1,71 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
@fieldwise_init
struct ValidationError(Copyable, Writable):
var field: String
var reason: String
def write_to(self, mut writer: Some[Writer]):
writer.write("ValidationError(", self.field, "): ", self.reason)
def validate_with_error(value: Int) raises -> Int:
if value < 0:
raise "value cannot be negative"
return value
def validate_typed(value: Int) raises ValidationError -> Int:
if value < 0:
raise ValidationError(field="value", reason="cannot be negative")
return value
# Pattern 1: Wrap an Error into a typed error at the boundary
def wrapped_validate(value: Int) raises ValidationError -> Int:
try:
return validate_with_error(value)
except e:
raise ValidationError(field="value", reason=String(e))
# Anti-pattern: bare raises erases type info at compile time
def validate_bare_raises(value: Int) raises -> Int:
return validate_typed(value)
def main():
# Pattern 1: Wrapping Error into typed errors
print("--- Wrapping Error into typed errors ---")
try:
_ = wrapped_validate(-5)
except e:
print("Field:", e.field, "Reason:", e.reason)
# Pattern 2: Catch typed errors with field access
print("--- Catching typed errors ---")
try:
_ = validate_typed(-5)
except e:
print("Field:", e.field, "Reason:", e.reason)
# Anti-pattern: bare raises loses compile-time type info
print("--- Bare raises (type erased) ---")
try:
_ = validate_bare_raises(-5)
except e:
# e is typed as Error, not ValidationError
# e.field would not compile here
print("Caught (no field access):", e)
@@ -0,0 +1,43 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
def process_record(id: Int) raises -> String:
if id < 0:
raise Error("invalid record ID: must be non-negative")
if id > 999:
raise Error("record not found")
return String("record_", id)
def main():
try:
for id in [5, 0, 1001, -3, 42]:
var result: String
try:
print()
print("try => id:", id)
if id == 0:
continue
result = process_record(id)
except e:
if "invalid" in String(e):
print("except => fatal:", e)
raise e
print("except => handled:", e)
else:
print("else => success:", result)
finally:
print("finally => done with id:", id)
except e:
print("\nre-raised error:", e)
@@ -0,0 +1,54 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
# Always raises, never returns — return type is Never
def panic(msg: String) raises -> Never:
raise Error(msg)
# Never raises, always returns — equivalent to: def safe_add(a: Int, b: Int) -> Int
def safe_add(a: Int, b: Int) raises Never -> Int:
return a + b
def get_value_or_panic(maybe: Optional[Int]) raises -> Int:
if maybe:
return maybe.value()
# Never substitutes for Int in this branch
panic("value is missing")
def main():
# A function that always raises
try:
panic("something went wrong")
except e:
print("Caught:", e)
# Never substituting for return type in control flow
try:
var value = get_value_or_panic(Optional(42))
print("Got value:", value)
except e:
print("Failed:", e)
try:
var value = get_value_or_panic(Optional[Int]())
print("Got value:", value)
except e:
print("Failed:", e)
# A function that never raises — no try block needed
var result = safe_add(3, 4)
print("safe_add(3, 4):", result)
@@ -0,0 +1,64 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
@fieldwise_init
struct NetworkError(Copyable, Writable):
var code: Int
def write_to(self, mut writer: Some[Writer]):
writer.write("NetworkError(code=", self.code, ")")
@fieldwise_init
struct ParseError(Copyable, Writable):
var position: Int
def write_to(self, mut writer: Some[Writer]):
writer.write("ParseError(position=", self.position, ")")
def run_action[
ErrorType: AnyType
](action: def() thin raises ErrorType -> Int) raises ErrorType -> Int:
return action()
def fetch_data() raises NetworkError -> Int:
raise NetworkError(code=404)
def parse_config() raises ParseError -> Int:
raise ParseError(position=42)
def get_value() -> Int:
return 99
def main():
# ErrorType inferred as NetworkError
try:
_ = run_action(fetch_data)
except e:
print("Network failure:", e)
# ErrorType inferred as ParseError
try:
_ = run_action(parse_config)
except e:
print("Parse failure:", e)
# ErrorType inferred as Never — no try block needed
var result = run_action(get_value)
print("Got value:", result)
@@ -0,0 +1,72 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
from std.reflection import *
@fieldwise_init
struct ConnectionError(Copyable, Writable):
var message: String
def write_to(self, mut writer: Some[Writer]):
writer.write("ConnectionError: ", self.message)
struct ResourceGuard(ImplicitlyCopyable):
var name: String
var suppress_errors: Bool
def __init__(out self, name: String, suppress_errors: Bool = False):
self.name = name
self.suppress_errors = suppress_errors
def __enter__(self) -> Self:
print("Acquiring:", self.name)
return self
def __exit__(self):
print("Releasing:", self.name, "(no error)")
def __exit__[ErrType: AnyType](self, err: ErrType) -> Bool:
comptime type_name = reflect[ErrType].name()
print("Releasing:", self.name)
print(" Error type:", type_name)
comptime if conforms_to(ErrType, Writable):
print(" Message:", err)
return self.suppress_errors
def use_connection() raises ConnectionError:
raise ConnectionError("connection timed out")
def main() raises:
# No error — calls __exit__(self)
print("--- No error ---")
with ResourceGuard("database"):
print("Working...")
# Typed error, not suppressed — calls __exit__[ErrType]
print("\n--- Error, not suppressed ---")
try:
with ResourceGuard("network"):
use_connection()
except e:
print("Caught:", e)
# Typed error, suppressed — __exit__[ErrType] returns True
print("\n--- Error, suppressed ---")
with ResourceGuard("cache", suppress_errors=True):
use_connection()
print("Continued after suppressed error")
@@ -0,0 +1,22 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
def func2() raises -> None:
raise Error("Intentional error")
def func1() raises -> None:
func2()
def main() raises:
func1()
@@ -0,0 +1,31 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
def func2() raises -> None:
raise Error("Intentional error")
def func1() raises -> None:
func2()
def main():
try:
func1()
except e:
print(e)
print("-" * 20)
var stack_trace = e.get_stack_trace()
if stack_trace:
print(stack_trace.value())
else:
print("No stack trace available")
@@ -0,0 +1,51 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
import std.time
from conditional_context_mgr import ConditionalTimer, flaky_identity
from std.testing import assert_raises, TestSuite
def test_conditional_timer_no_error() raises:
with ConditionalTimer():
print("Beginning no-error execution")
std.time.sleep(0.1)
var i = 1
_ = flaky_identity(i)
print("Ending no-error execution")
def test_conditional_timer_suppressed_error() raises:
var i = 2
with assert_raises(contains="just a warning"):
_ = flaky_identity(i)
with ConditionalTimer():
print("Beginning no-error execution")
std.time.sleep(0.1)
_ = flaky_identity(i)
print("Ending no-error execution")
def test_conditional_timer_propagated_error() raises:
with assert_raises(contains="really bad"):
with ConditionalTimer():
print("Beginning propagated error execution")
std.time.sleep(0.1)
var i = 4
_ = flaky_identity(i)
# We should not reach this line
def main() raises:
TestSuite.discover_tests[__functions_in_module()]().run()
@@ -0,0 +1,36 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
import std.time
from context_mgr import Timer
from std.testing import assert_raises, TestSuite
def test_timer_no_error() raises:
with Timer():
print("Beginning no-error execution")
std.time.sleep(0.1)
print("Ending no-error execution")
def test_timer_error() raises:
with assert_raises(contains="simulated error"):
with Timer():
print("Beginning error execution")
std.time.sleep(0.1)
raise "simulated error"
# We should not reach this line
def main() raises:
TestSuite.discover_tests[__functions_in_module()]().run()
@@ -0,0 +1,47 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
from std.testing import assert_equal, assert_raises, assert_true, TestSuite
from enumerated_errors import FileError, open_file
def test_open_file_success() raises:
assert_equal(open_file("/data"), "Contents of /data")
def test_not_found() raises:
with assert_raises(contains="not_found"):
_ = open_file("")
def test_permission_denied() raises:
with assert_raises(contains="permission_denied"):
_ = open_file("/secret")
def test_already_exists() raises:
with assert_raises(contains="already_exists"):
_ = open_file("/existing")
def test_variant_equality() raises:
assert_true(FileError.not_found == FileError.not_found)
assert_true(FileError.permission_denied == FileError.permission_denied)
def test_variant_inequality() raises:
assert_true(FileError.not_found != FileError.permission_denied)
def main() raises:
TestSuite.discover_tests[__functions_in_module()]().run()
@@ -0,0 +1,54 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
from std.testing import assert_equal, assert_raises, TestSuite
from error_interaction import (
wrapped_validate,
validate_typed,
validate_bare_raises,
)
def test_wrapped_validate_pass() raises:
assert_equal(wrapped_validate(5), 5)
def test_wrapped_validate_fail() raises:
with assert_raises(contains="cannot be negative"):
_ = wrapped_validate(-5)
def test_wrapped_validate_field_access() raises:
try:
_ = wrapped_validate(-5)
except e:
assert_equal(e.field, "value")
def test_validate_typed_pass() raises:
assert_equal(validate_typed(5), 5)
def test_validate_typed_fail() raises:
with assert_raises(contains="cannot be negative"):
_ = validate_typed(-5)
def test_bare_raises_erases_type() raises:
# validate_bare_raises erases type info — only Error is caught
with assert_raises(contains="cannot be negative"):
_ = validate_bare_raises(-5)
def main() raises:
TestSuite.discover_tests[__functions_in_module()]().run()
@@ -0,0 +1,38 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
from handle_error import process_record
from std.testing import assert_equal, assert_raises, TestSuite
def test_process_record_success() raises:
assert_equal(process_record(0), "record_0")
assert_equal(process_record(5), "record_5")
assert_equal(process_record(999), "record_999")
def test_process_record_not_found() raises:
with assert_raises(contains="record not found"):
_ = process_record(1000)
with assert_raises(contains="record not found"):
_ = process_record(1001)
def test_process_record_invalid_id() raises:
with assert_raises(contains="invalid record ID: must be non-negative"):
_ = process_record(-1)
with assert_raises(contains="invalid record ID: must be non-negative"):
_ = process_record(-3)
def main() raises:
TestSuite.discover_tests[__functions_in_module()]().run()
@@ -0,0 +1,38 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
from std.testing import assert_equal, assert_raises, TestSuite
from never_type import panic, get_value_or_panic, safe_add
def test_panic_always_raises() raises:
with assert_raises(contains="boom"):
panic("boom")
def test_get_value_with_some() raises:
assert_equal(get_value_or_panic(Optional(42)), 42)
def test_get_value_with_none() raises:
with assert_raises(contains="value is missing"):
_ = get_value_or_panic(Optional[Int]())
def test_safe_add() raises:
assert_equal(safe_add(3, 4), 7)
assert_equal(safe_add(0, 0), 0)
def main() raises:
TestSuite.discover_tests[__functions_in_module()]().run()
@@ -0,0 +1,33 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
from std.testing import assert_equal, assert_raises, TestSuite
from parametric_raises import run_action, fetch_data, parse_config, get_value
def test_run_action_network_error() raises:
with assert_raises(contains="NetworkError"):
_ = run_action(fetch_data)
def test_run_action_parse_error() raises:
with assert_raises(contains="ParseError"):
_ = run_action(parse_config)
def test_run_action_no_error() raises:
assert_equal(run_action(get_value), 99)
def main() raises:
TestSuite.discover_tests[__functions_in_module()]().run()
@@ -0,0 +1,41 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
from std.testing import assert_equal, assert_raises, TestSuite
from typed_errors import ValidationError, validate_username
def test_valid_username() raises:
assert_equal(validate_username("alice"), "alice")
def test_empty_username_raises() raises:
with assert_raises(contains="cannot be empty"):
_ = validate_username("")
def test_short_username_raises() raises:
with assert_raises(contains="must be at least 3 characters"):
_ = validate_username("ab")
def test_field_access() raises:
try:
_ = validate_username("")
except e:
assert_equal(e.field, "username")
assert_equal(e.reason, "cannot be empty")
def main() raises:
TestSuite.discover_tests[__functions_in_module()]().run()
@@ -0,0 +1,137 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
from std.testing import assert_equal, assert_raises, assert_true, TestSuite
from typed_errors_edge_cases import (
NetworkError,
ParseError,
ApplicationError,
fetch_data,
parse_data,
fetch_and_parse,
level1,
level2,
level3,
reraise_with_logging,
reraise_as_different_type,
reraise_modified,
suppress_error,
suppress_and_continue,
)
def test_network_error_fields() raises:
"""Test NetworkError field access."""
try:
_ = fetch_data()
except e:
assert_equal(e.code, 404)
assert_equal(e.message, "Resource not found")
def test_parse_error_fields() raises:
"""Test ParseError field access."""
try:
_ = parse_data("test")
except e:
assert_equal(e.position, 0)
assert_equal(e.expected, "integer")
def test_nested_try_blocks() raises:
"""Test nested try blocks with different error types."""
try:
_ = fetch_and_parse()
except e:
assert_equal(e.source, "network")
assert_true(e.details.find("NetworkError") >= 0)
def test_error_propagation_level3() raises:
"""Test error originates from level3."""
with assert_raises(contains="Server error"):
level3()
def test_error_propagation_level2() raises:
"""Test error propagates through level2."""
with assert_raises(contains="Server error"):
level2()
def test_error_propagation_level1() raises:
"""Test error propagates through entire chain."""
try:
level1()
except e:
assert_equal(e.code, 500)
assert_equal(e.message, "Server error")
def test_reraise_with_logging() raises:
"""Test re-raising preserves error."""
try:
_ = reraise_with_logging()
except e:
assert_equal(e.code, 404)
assert_equal(e.message, "Resource not found")
def test_reraise_as_different_type() raises:
"""Test converting error type on re-raise."""
try:
_ = reraise_as_different_type()
except e:
assert_equal(e.source, "network")
assert_true(e.details.find("404") >= 0)
def test_reraise_modified() raises:
"""Test modifying error on re-raise."""
try:
_ = reraise_modified()
except e:
assert_equal(e.code, 404)
assert_true(e.message.find("[Modified]") >= 0)
def test_suppress_error_returns_default() raises:
"""Test error suppression returns default value."""
var result = suppress_error()
assert_equal(result, "default value")
def test_suppress_and_continue() raises:
"""Test error suppression allows continuation."""
# This should complete without raising
suppress_and_continue()
def test_application_error_from_network() raises:
"""Test ApplicationError factory from NetworkError."""
var net_err = NetworkError(code=500, message="test")
var app_err = ApplicationError.from_network(net_err)
assert_equal(app_err.source, "network")
assert_true(app_err.details.find("500") >= 0)
def test_application_error_from_parse() raises:
"""Test ApplicationError factory from ParseError."""
var parse_err = ParseError(position=10, expected="number")
var app_err = ApplicationError.from_parse(parse_err)
assert_equal(app_err.source, "parse")
assert_true(app_err.details.find("10") >= 0)
def main() raises:
TestSuite.discover_tests[__functions_in_module()]().run()
@@ -0,0 +1,187 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
from std.testing import assert_raises, assert_equal, assert_true, TestSuite
from typed_errors_testing import (
ValidationError,
ConfigError,
validate_username,
validate_age,
load_config,
)
# =============================================================================
# Tests for assert_raises with typed errors
# =============================================================================
def test_assert_raises_basic() raises:
"""Test assert_raises catches typed errors."""
with assert_raises():
validate_username("")
def test_assert_raises_contains_message() raises:
"""Test assert_raises(contains=...) matches error messages."""
with assert_raises(contains="cannot be empty"):
validate_username("")
def test_assert_raises_contains_reason() raises:
"""Test assert_raises matches partial reason."""
with assert_raises(contains="at least 3"):
validate_username("ab")
def test_assert_raises_contains_field() raises:
"""Test assert_raises matches field name in output."""
with assert_raises(contains="field: username"):
validate_username("")
def test_assert_raises_config_error() raises:
"""Test assert_raises with ConfigError."""
with assert_raises(contains="key not found"):
_ = load_config("missing")
def test_assert_raises_config_invalid() raises:
"""Test assert_raises with different ConfigError reason."""
with assert_raises(contains="invalid value format"):
_ = load_config("invalid")
# =============================================================================
# Tests for type verification via field access
# =============================================================================
def test_verify_validation_error_fields() raises:
"""Test verifying ValidationError type via field access."""
var field = ""
var reason = ""
try:
validate_username("")
except e:
field = e.field
reason = e.reason
assert_equal(field, "username")
assert_equal(reason, "cannot be empty")
def test_verify_config_error_fields() raises:
"""Test verifying ConfigError type via field access."""
var key = ""
var message = ""
try:
_ = load_config("missing")
except e:
key = e.key
message = e.message
assert_equal(key, "missing")
assert_equal(message, "key not found")
def test_verify_age_validation() raises:
"""Test age validation error fields."""
var field = ""
var reason = ""
try:
validate_age(-1)
except e:
field = e.field
reason = e.reason
assert_equal(field, "age")
assert_equal(reason, "cannot be negative")
# =============================================================================
# Tests for workaround pattern (flag variable)
# =============================================================================
def test_flag_pattern_error_raised() raises:
"""Test flag pattern confirms error was raised."""
var raised = False
try:
validate_username("")
except e:
raised = True
_ = e.field # Proves type
assert_true(raised, "Error should be raised")
def test_flag_pattern_no_error() raises:
"""Test flag pattern when no error is raised."""
var raised = False
try:
validate_username("validname")
except e:
raised = True
assert_true(not raised, "No error should be raised")
def test_flag_pattern_multiple_conditions() raises:
"""Test flag pattern with multiple error conditions."""
var empty_raised = False
var short_raised = False
try:
validate_username("")
except e:
empty_raised = True
assert_equal(e.reason, "cannot be empty")
try:
validate_username("ab")
except e:
short_raised = True
assert_equal(e.reason, "must be at least 3 characters")
assert_true(empty_raised, "Empty username should raise")
assert_true(short_raised, "Short username should raise")
# =============================================================================
# Tests for successful operations (no error)
# =============================================================================
def test_valid_username() raises:
"""Test valid username does not raise."""
# Should complete without error
validate_username("validuser")
def test_valid_age() raises:
"""Test valid age does not raise."""
validate_age(25)
def test_valid_config() raises:
"""Test valid config key returns value."""
var value = load_config("database")
assert_equal(value, "value_for_database")
def main() raises:
TestSuite.discover_tests[__functions_in_module()]().run()
@@ -0,0 +1,74 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
from std.testing import assert_equal, assert_raises, assert_true, TestSuite
from variant_errors import FileError, NotFoundError, PermissionError, open_file
def test_open_file_success() raises:
assert_equal(open_file("/data"), "Contents of /data")
def test_not_found_error() raises:
with assert_raises(contains="file not found"):
_ = open_file("")
def test_permission_denied_error() raises:
with assert_raises(contains="permission denied"):
_ = open_file("/secret")
def test_not_found_fields() raises:
var caught = False
var path = String("")
try:
_ = open_file("")
except e:
caught = True
if e.isa[NotFoundError]():
path = e[NotFoundError].path
assert_true(caught, "Expected NotFoundError to be raised")
assert_equal(path, "")
def test_permission_denied_fields() raises:
var caught = False
var path = String("")
var role = String("")
try:
_ = open_file("/secret")
except e:
caught = True
if e.isa[PermissionError]():
path = e[PermissionError].path
role = e[PermissionError].required_role
assert_true(caught, "Expected PermissionError to be raised")
assert_equal(path, "/secret")
assert_equal(role, "admin")
def test_variant_isa_identification() raises:
var is_not_found = False
var is_permission = False
try:
_ = open_file("")
except e:
is_not_found = e.isa[NotFoundError]()
is_permission = e.isa[PermissionError]()
assert_true(is_not_found, "Expected isa[NotFoundError] to be True")
assert_true(not is_permission, "Expected isa[PermissionError] to be False")
def main() raises:
TestSuite.discover_tests[__functions_in_module()]().run()
@@ -0,0 +1,51 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
@fieldwise_init
struct ValidationError(Copyable, Writable):
var field: String
var reason: String
def write_to(self, mut writer: Some[Writer]):
writer.write("ValidationError(", self.field, "): ", self.reason)
def validate_username(username: String) raises ValidationError -> String:
if username.byte_length() == 0:
raise ValidationError(field="username", reason="cannot be empty")
if username.count_codepoints() < 3:
raise ValidationError(
field="username", reason="must be at least 3 characters"
)
return username
def main():
# Valid username
try:
print(validate_username("alice"))
except e:
print("Error in field '" + e.field + "': " + e.reason)
# Error: empty username
try:
print(validate_username(""))
except e:
print("Error in field '" + e.field + "': " + e.reason)
# Error: too-short username
try:
print(validate_username("ab"))
except e:
print("Error in field '" + e.field + "': " + e.reason)
@@ -0,0 +1,226 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
"""Demonstrates edge cases and patterns for typed error handling.
Key findings:
- Multiple except clauses are NOT supported (use nested try blocks instead)
- Python-style `except ErrorType as e:` syntax is NOT supported
- Errors propagate correctly through multiple function calls
- Re-raising works with `raise e^` (transfers ownership)
- Error suppression works by catching and not re-raising
- Compiler warns about unreachable except blocks
Compiler behaviors documented:
- `except ErrorType as e:` -> "expected ':' after 'except'"
- Try block with non-raising code -> "except logic is unreachable"
"""
@fieldwise_init
struct NetworkError(Copyable, Writable):
"""Error for network operations."""
var code: Int
var message: String
def write_to(self, mut writer: Some[Writer]):
writer.write("NetworkError[", self.code, "]: ", self.message)
@fieldwise_init
struct ParseError(Copyable, Writable):
"""Error for parsing operations."""
var position: Int
var expected: String
def write_to(self, mut writer: Some[Writer]):
writer.write(
"ParseError at ", self.position, ": expected ", self.expected
)
@fieldwise_init
struct ApplicationError(Copyable, Writable):
"""Unified error type for application-level errors."""
var source: String
var details: String
def write_to(self, mut writer: Some[Writer]):
writer.write("ApplicationError[", self.source, "]: ", self.details)
@staticmethod
def from_network(e: NetworkError) -> Self:
"""Convert a NetworkError to ApplicationError."""
return Self(source="network", details=String(e))
@staticmethod
def from_parse(e: ParseError) -> Self:
"""Convert a ParseError to ApplicationError."""
return Self(source="parse", details=String(e))
# =============================================================================
# Pattern 1: Nested try blocks for handling different error types
# =============================================================================
def fetch_data() raises NetworkError -> String:
"""Simulate fetching data that may fail."""
raise NetworkError(code=404, message="Resource not found")
def parse_data(data: String) raises ParseError -> Int:
"""Simulate parsing data that may fail."""
raise ParseError(position=0, expected="integer")
def fetch_and_parse() raises ApplicationError -> Int:
"""Handle different error types using nested try blocks.
Since Mojo only supports one except clause per try block,
use nested blocks to handle different error types.
"""
var data: String
try:
data = fetch_data()
except e:
raise ApplicationError.from_network(e)
try:
return parse_data(data)
except e:
raise ApplicationError.from_parse(e)
# =============================================================================
# Pattern 2: Error propagation through call chain
# =============================================================================
def level3() raises NetworkError:
"""Deepest level - raises the error."""
raise NetworkError(code=500, message="Server error")
def level2() raises NetworkError:
"""Middle level - propagates error unchanged."""
level3()
def level1() raises NetworkError:
"""Top level - propagates error unchanged."""
level2()
# =============================================================================
# Pattern 3: Re-raising errors
# =============================================================================
def reraise_with_logging() raises NetworkError -> String:
"""Catch, log, and re-raise the same error."""
try:
return fetch_data()
except e:
print("Logging before re-raise:", e)
raise e^ # Use ^ to transfer ownership
def reraise_as_different_type() raises ApplicationError -> String:
"""Catch one type and raise a different type."""
try:
return fetch_data()
except e:
raise ApplicationError.from_network(e)
def reraise_modified() raises NetworkError -> String:
"""Catch, modify, and raise a new error."""
try:
return fetch_data()
except e:
raise NetworkError(code=e.code, message="[Modified] " + e.message)
# =============================================================================
# Pattern 4: Error suppression
# =============================================================================
def suppress_error() -> String:
"""Catch an error and return a default value instead of re-raising."""
try:
return fetch_data()
except e:
print("Suppressed error:", e)
return "default value"
def suppress_and_continue():
"""Catch an error and continue execution."""
try:
_ = fetch_data()
except e:
print("Ignored error:", e)
print("Continuing after suppressed error")
# =============================================================================
# Demonstration
# =============================================================================
def main():
print("=== Pattern 1: Nested try blocks ===")
try:
_ = fetch_and_parse()
except e:
print("Unified error:", e)
print(" Source:", e.source)
print("\n=== Pattern 2: Error propagation ===")
try:
level1()
except e:
print("Propagated through 3 levels:", e)
print("\n=== Pattern 3: Re-raising ===")
print("\n--- With logging ---")
try:
_ = reraise_with_logging()
except e:
print("After re-raise:", e)
print("\n--- As different type ---")
try:
_ = reraise_as_different_type()
except e:
print("Converted:", e)
print("\n--- Modified ---")
try:
_ = reraise_modified()
except e:
print("Modified:", e)
print("\n=== Pattern 4: Error suppression ===")
print("\n--- Return default ---")
var result = suppress_error()
print("Got result:", result)
print("\n--- Continue execution ---")
suppress_and_continue()
@@ -0,0 +1,208 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
"""Demonstrates testing typed errors with the Mojo testing framework.
Key findings:
- assert_raises() works correctly with typed errors
- assert_raises(contains=...) matches typed error message strings
- Cannot assert specific error TYPE, only that some error was raised
- Cannot mix `Error`-raising functions inside typed error try blocks
- Workaround: Use flag variables and verify fields after try block
Recommended patterns:
1. Use assert_raises(contains=...) for message verification
2. Manually catch and verify fields for type verification
3. Use flag variables to avoid mixing error types in try blocks
"""
from std.testing import assert_raises, assert_equal, assert_true
@fieldwise_init
struct ValidationError(Copyable, Writable):
"""A typed error for validation failures."""
var field: String
var reason: String
def write_to(self, mut writer: Some[Writer]):
writer.write(
"ValidationError: ", self.reason, " (field: ", self.field, ")"
)
@fieldwise_init
struct ConfigError(Copyable, Writable):
"""A typed error for configuration problems."""
var key: String
var message: String
def write_to(self, mut writer: Some[Writer]):
writer.write("ConfigError[", self.key, "]: ", self.message)
# =============================================================================
# Functions that raise typed errors
# =============================================================================
def validate_username(name: String) raises ValidationError:
"""Validate a username."""
if not name:
raise ValidationError(field="username", reason="cannot be empty")
if name.count_codepoints() < 3:
raise ValidationError(
field="username", reason="must be at least 3 characters"
)
def validate_age(age: Int) raises ValidationError:
"""Validate an age value."""
if age < 0:
raise ValidationError(field="age", reason="cannot be negative")
if age > 150:
raise ValidationError(field="age", reason="must be realistic")
def load_config(key: String) raises ConfigError -> String:
"""Load a configuration value."""
if key == "missing":
raise ConfigError(key=key, message="key not found")
if key == "invalid":
raise ConfigError(key=key, message="invalid value format")
return "value_for_" + key
# =============================================================================
# Pattern 1: Using assert_raises with typed errors
# =============================================================================
def demonstrate_assert_raises() raises:
"""Shows assert_raises works with typed errors."""
print("=== Pattern 1: assert_raises ===")
# Basic assertion - just check that an error is raised
print("Testing empty username...")
with assert_raises():
validate_username("")
print(" Passed: Error was raised")
# With contains - check error message
print("Testing short username...")
with assert_raises(contains="at least 3 characters"):
validate_username("ab")
print(" Passed: Message contains expected text")
# Can match field names in error output
print("Testing field name in message...")
with assert_raises(contains="field: username"):
validate_username("")
print(" Passed: Field name found in message")
# =============================================================================
# Pattern 2: Verifying error type via field access
# =============================================================================
def demonstrate_type_verification() raises:
"""Shows how to verify specific error type was raised."""
print("\n=== Pattern 2: Type verification ===")
# Capture error fields to verify type
var error_field = ""
var error_reason = ""
try:
validate_username("")
except e:
# Field access proves this is ValidationError
error_field = e.field
error_reason = e.reason
# Verify after try block (avoid mixing error types)
assert_equal(error_field, "username")
assert_equal(error_reason, "cannot be empty")
print("Verified ValidationError with correct fields")
# =============================================================================
# Pattern 3: Testing multiple error scenarios
# =============================================================================
def demonstrate_multiple_scenarios() raises:
"""Shows testing various error conditions."""
print("\n=== Pattern 3: Multiple scenarios ===")
# Test different error conditions for the same function
print("Testing username validation scenarios...")
with assert_raises(contains="cannot be empty"):
validate_username("")
with assert_raises(contains="at least 3 characters"):
validate_username("ab")
print(" All scenarios passed")
# Test different functions with different error types
print("Testing config loading...")
with assert_raises(contains="key not found"):
_ = load_config("missing")
with assert_raises(contains="invalid value format"):
_ = load_config("invalid")
print(" All scenarios passed")
# =============================================================================
# Pattern 4: Workaround for mixing error types
# =============================================================================
def demonstrate_workaround() raises:
"""Shows workaround for the error type mixing limitation."""
print("\n=== Pattern 4: Error type workaround ===")
# Problem: Cannot call assert_true inside typed error try block
# Solution: Use flag variable
var raised = False
try:
validate_age(-1)
except e:
raised = True
# Can still verify fields here
_ = e.field # Would fail to compile if not ValidationError
# Check flag outside try block
assert_true(raised, "Expected ValidationError")
print("Error was raised and caught correctly")
# =============================================================================
# Main demonstration
# =============================================================================
def main() raises:
demonstrate_assert_raises()
demonstrate_type_verification()
demonstrate_multiple_scenarios()
demonstrate_workaround()
print("\nAll demonstrations completed successfully!")
@@ -0,0 +1,72 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
from std.utils import Variant
@fieldwise_init
struct NotFoundError(Copyable, Writable):
var path: String
def write_to(self, mut writer: Some[Writer]):
writer.write("file not found: ", self.path)
@fieldwise_init
struct PermissionError(Copyable, Writable):
var path: String
var required_role: String
def write_to(self, mut writer: Some[Writer]):
writer.write(
"permission denied on ",
self.path,
" (requires ",
self.required_role,
")",
)
comptime FileError = Variant[NotFoundError, PermissionError]
def open_file(path: String) raises FileError -> String:
if not path:
raise FileError(NotFoundError(""))
if path == "/secret":
raise FileError(PermissionError("/secret", "admin"))
return "Contents of " + path
def handle_file_error(e: FileError):
if e.isa[NotFoundError]():
print("Not found:", e[NotFoundError])
elif e.isa[PermissionError]():
print("Access denied:", e[PermissionError])
def main():
try:
print(open_file("/data"))
except e:
handle_file_error(e)
try:
print(open_file(""))
except e:
handle_file_error(e)
try:
print(open_file("/secret"))
except e:
handle_file_error(e)
@@ -0,0 +1,386 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
# test_closures.mojo
# Tests for closures.mdx code examples.
# Skip: empty capture error example (deliberate compile error),
# parallelize (threading + signature may vary).
from std.testing import assert_equal, assert_true
# --- Intro: scale ---
def test_scale() raises:
"""Intro example: imm capture with multiplier."""
var multiplier = 3
def scale(x: Int) {imm multiplier} -> Int:
return x * multiplier
assert_equal(scale(5), 15)
# --- The capture list: mixed imm + mut ---
def test_capture_list_imm_mut() raises:
"""Capture list example: imm x, mut y."""
var x = 10
var y = 20
def inner(z: Int) {imm x, mut y} -> Int:
y += z
return x + y
assert_equal(inner(5), 35)
assert_equal(y, 25)
# --- Capture by immutable reference: imm ---
def test_imm_threshold() raises:
"""Explicit imm capture: is_over checks threshold."""
var threshold = 100
def is_over(x: Int) {imm threshold} -> Bool:
return x > threshold
assert_true(not is_over(50))
assert_true(is_over(200))
def test_imm_sees_live_updates() raises:
"""`imm` captures a reference, so it sees later mutations."""
var limit = 10
def check(x: Int) {imm limit} -> Bool:
return x < limit
assert_true(check(5))
limit = 3
assert_true(not check(5))
def test_imm_implicit() raises:
"""Implicit `imm`: {imm} captures all used outer values."""
var a = 1
var b = 2
def sum_ab() {imm} -> Int:
return a + b
assert_equal(sum_ab(), 3)
# --- Capture by mutable reference: mut ---
def test_mut_accumulate() raises:
"""Explicit mut capture: accumulate modifies outer total."""
var total = 0
def accumulate(x: Int) {mut total}:
total += x
accumulate(10)
accumulate(20)
assert_equal(total, 30)
def test_mut_implicit() raises:
"""Implicit `mut`: {mut} captures all used outer values mutably."""
var count = 0
var items = List[String]()
def record(name: String) {mut}:
items.append(name)
count += 1
record("alpha")
record("beta")
assert_equal(count, 2)
assert_equal(len(items), 2)
assert_equal(items[0], "alpha")
assert_equal(items[1], "beta")
# --- Capture by copy: var ---
def test_var_snapshot() raises:
"""Explicit `var` capture: closure keeps value at definition time."""
var snapshot_val = 42
def frozen() {var snapshot_val} -> Int:
return snapshot_val
snapshot_val = 999
assert_equal(frozen(), 42)
_ = snapshot_val
def test_var_implicit() raises:
"""Implicit `var`: {var} copies all used outer values."""
var x = 10
var y = 20
def snap() {var} -> Int:
return x + y
x = 0
y = 0
assert_equal(snap(), 30)
_ = x
_ = y
# --- Move capture: var name^ ---
def test_move_capture() raises:
"""Move capture: `var data^` transfers ownership into closure."""
var data: List[Int] = [1, 2, 3]
def take_data() {var data^} -> Int:
return len(data)
assert_equal(take_data(), 3)
# data is consumed; can't be used after this point
# --- Copyable closures: var^ ---
def test_var_caret_copyable() raises:
"""Copyable closure: `{var^}` allows assigning closure to new var."""
var label = "sensor-1"
def tag() {var^} -> String:
return label
var also_tag = tag
assert_equal(tag(), "sensor-1")
assert_equal(also_tag(), "sensor-1")
# --- Caller-determined mutability: ref ---
def test_ref_capture() raises:
"""Ref capture: closure adapts to caller's mutability context."""
def apply_to(ref items: List[Int]) -> Int:
def first() {ref items} -> Int:
return items[0]
return first()
var nums: List[Int] = [10, 20, 30]
assert_equal(apply_to(nums), 10)
def test_ref_capture_mutability() raises:
"""Ref capture with comptime if: verifies mut vs immut propagation."""
def check_mutability(ref items: List[Int]) -> String:
def report() {ref items} -> String:
comptime if origin_of(items).mut:
return "mut"
else:
return "immut"
return report()
def from_read(imm xs: List[Int]) -> String:
return check_mutability(xs)
def from_mut(mut xs: List[Int]) -> String:
return check_mutability(xs)
var nums: List[Int] = [10, 20, 30]
assert_equal(from_read(nums), "immut")
assert_equal(from_mut(nums), "mut")
# --- Empty capture list: {} ---
def test_empty_capture_list() raises:
"""Empty capture: {} closure uses only its own arguments."""
def doubled(x: Int) {} -> Int:
return x * 2
assert_equal(doubled(5), 10)
# NOTE: The empty capture error example ({} referencing outer var)
# is a deliberate compile error and cannot be tested at runtime.
# --- Mixing capture conventions ---
def test_mixed_conventions() raises:
"""Mixed capture list: `imm` + `mut` + `var` in one closure."""
var config = "prod"
var count = 0
var label = "run-1"
def process() {imm config, mut count, var label} -> String:
count += 1
return config + " " + String(count) + " " + label
assert_equal(process(), "prod 1 run-1")
label = "run-2"
assert_equal(process(), "prod 2 run-1")
_ = label
def test_bare_name_defaults_to_imm() raises:
"""Bare name in capture list defaults to `imm` convention."""
var x = 10
def show() {x} -> Int:
return x
assert_equal(show(), 10)
# --- Setting a default convention ---
def test_default_convention() raises:
"""Implicit default + explicit override in one capture list."""
var a = 1
var b = 2
var z = "snapshot"
def mixed() {mut, var z} -> String:
a += 10
b += 20
return String(a) + " " + String(b) + " " + z
assert_equal(mixed(), "11 22 snapshot")
z = "changed"
assert_equal(mixed(), "21 42 snapshot")
_ = z
# --- Closures in practice: accumulating state ---
def test_accumulating_log() raises:
"""Practical example: mut capture builds a log across calls."""
var log = List[String]()
def record(event: String) {mut log}:
log.append(event)
record("started")
record("processed item")
record("finished")
assert_equal(len(log), 3)
assert_equal(log[0], "started")
assert_equal(log[1], "processed item")
assert_equal(log[2], "finished")
# --- Closures in practice: configurable behavior ---
def test_greet_all() raises:
"""Practical example: parametric function accepts closure."""
var results = List[String]()
def greet_all[G: def(String) -> None](names: List[String], greet: G):
for n in names:
greet(n)
var names: List[String] = ["Alice", "Bob"]
var greeting = "Hello"
def greeter(name: String) {imm greeting, mut results}:
results.append(greeting + ", " + name + "!")
greet_all(names, greeter)
assert_equal(len(results), 2)
assert_equal(results[0], "Hello, Alice!")
assert_equal(results[1], "Hello, Bob!")
greeting = "Hi"
greet_all(names, greeter)
assert_equal(len(results), 4)
assert_equal(results[2], "Hi, Alice!")
assert_equal(results[3], "Hi, Bob!")
# NOTE: The parallelize example is skipped. It requires threading
# and the exact API signature may vary across stdlib versions.
# However, it works, and here it is for your manual testing:
#
# from max.algorithm import parallelize
#
# def main():
# var results = List[Int](length=8, fill=0)
#
# def work(i: Int) {mut results}:
# results[i] = i * i
#
# parallelize(work, 8)
# print(results) # [0, 1, 4, 9, 16, 25, 36, 49]
def main() raises:
# Intro
test_scale()
# The capture list
test_capture_list_imm_mut()
# read
test_imm_threshold()
test_imm_sees_live_updates()
test_imm_implicit()
# mut
test_mut_accumulate()
test_mut_implicit()
# var
test_var_snapshot()
test_var_implicit()
# Move capture
test_move_capture()
# Copyable closures
test_var_caret_copyable()
# ref
test_ref_capture()
test_ref_capture_mutability()
# Empty capture
test_empty_capture_list()
# Mixed conventions
test_mixed_conventions()
test_bare_name_defaults_to_imm()
test_default_convention()
# Practice examples
test_accumulating_log()
test_greet_all()
@@ -0,0 +1,212 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
# tests.mojo
# Tests for lambda.mdx code examples.
#
# Not tested (no runnable behavior to assert from this file):
# - the bare lambda expression `lambda (x: Int) -> Int: x + 1`, shown
# without a call site
# - the inline-lambda call fragment `transform(lambda ..., values)`, shown
# without surrounding context
# - the two behavior fragments under "Delegating behavior"
# (`lambda (value: Int) -> c_int: c_int(value)` and the doubler)
# - `inplace_transform[lambda (x: Int) -> Int: x ** factor](numbers)`, which
# the page presents as failing to compile: capturing `factor` makes the
# lambda a closure, so it can't bind the `thin` function pointer parameter
from std.ffi import external_call, c_int, c_size_t
from std.sys import size_of
from std.testing import assert_almost_equal, assert_equal
# --- Higher-order helpers defined on the page ---
def bubble_sort[
T: ImplicitlyCopyable & Deinitable, F: def(T, T) -> Bool, //
](compare_fn: F, mut values: List[T]):
for end in reversed(range(len(values))):
for i in range(end):
if compare_fn(values[i], values[i + 1]):
values[i], values[i + 1] = values[i + 1], values[i]
def inplace_transform[
T: ImplicitlyCopyable & Deinitable, //, f: def(T) thin -> T
](mut list: List[T]):
for index in range(len(list)):
list[index] = f(list[index])
def transform[
T: Copyable, U: Copyable, F: def(T) -> U, //
](f: F, list: List[T]) -> List[U]:
return [f(item) for item in list]
def apply[T: Copyable, F: def(T) -> None, //](f: F, i: List[T]):
for item in i:
f(item)
def increment[
Key: ImplicitlyCopyable & Hashable & Equatable & Deinitable
](mut d: Dict[Key, Int], key: Key):
d[key] = d.get(key, 0) + 1
# --- Creating a lambda: a lambda and the named function it mirrors ---
def inc_named(x: Int) -> Int:
return x + 1
def test_creating_a_lambda() raises:
var inc = lambda (x: Int) -> Int: x + 1
assert_equal(inc(4), 5)
# The page states the two forms produce the same behavior.
assert_equal(inc(4), inc_named(4))
# --- Supplying behavior: a named comparator and an inline lambda agree ---
def ascending(x: Int, y: Int) -> Bool:
return x > y
def test_bubble_sort_named_comparator() raises:
var values: List[Int] = [3, 1, 4, 1, 5, 9]
bubble_sort(ascending, values)
assert_equal(values, [1, 1, 3, 4, 5, 9])
def test_bubble_sort_inline_lambda() raises:
var values: List[Int] = [3, 1, 4, 1, 5, 9]
bubble_sort(lambda (a: Int, b: Int) -> Bool: a > b, values)
assert_equal(values, [1, 1, 3, 4, 5, 9])
def test_bubble_sort_flipped_comparison() raises:
# The page notes that flipping the comparison reverses the order.
var values: List[Int] = [3, 1, 4, 1, 5, 9]
bubble_sort(lambda (a: Int, b: Int) -> Bool: a < b, values)
assert_equal(values, [9, 5, 4, 3, 1, 1])
# --- Thin lambdas: a thin lambda binds a `thin` function pointer parameter ---
def test_inplace_transform_thin_lambda() raises:
var numbers: List[Int] = [1, 2, 3, 4, 5]
inplace_transform[lambda (x: Int) -> Int: x * 2](numbers)
assert_equal(numbers, [2, 4, 6, 8, 10])
# --- Closures with direct calls: the closure reads current values ---
def test_closure_direct_call() raises:
var x, y = 3.0, 4.5
var magnitude = lambda -> Float64: (x**2 + y**2) ** 0.5
assert_almost_equal(magnitude(), 5.408326913175031)
# An `imm` capture holds a reference, so a later call sees the new values.
x, y = -2.5, 1.5
assert_almost_equal(magnitude(), 2.9154759474226504)
# --- Runtime arguments: a capturing lambda passes where a thin one can't ---
def test_transform_capturing_lambda() raises:
var numbers: List[Int] = [2, 4, 6, 8, 10]
var factor = 3
var transformed = transform(lambda (x: Int) -> Int: x**factor, numbers)
assert_equal(transformed, [8, 64, 216, 512, 1000])
factor = 2
transformed = transform(lambda (x: Int) -> Int: x**factor, numbers)
assert_equal(transformed, [4, 16, 36, 64, 100])
# --- Capturing and mutating state: the word-length histogram ---
def test_histogram() raises:
var words = (
String(
"Lorem ipsum dolor sit amet, consectetur adipiscing elit. "
"Sed fringilla nons sapien quis pharetra."
)
.replace(",", "")
.replace(".", "")
)
var word_list = [String(w) for w in words.split(" ")]
comptime counter = lambda (x: String) -> Int: x.count_codepoints()
var counts = transform(counter, word_list)
assert_equal(counts, [5, 5, 5, 3, 4, 11, 10, 4, 3, 9, 4, 6, 4, 8])
var histogram: Dict[Int, Int] = {}
var collector = lambda (n: Int) {mut histogram}: increment(histogram, n)
apply(collector, counts)
assert_equal(len(histogram), 8)
assert_equal(histogram[5], 3)
assert_equal(histogram[4], 4)
assert_equal(histogram[3], 2)
assert_equal(histogram[11], 1)
assert_equal(histogram[10], 1)
assert_equal(histogram[9], 1)
assert_equal(histogram[6], 1)
assert_equal(histogram[8], 1)
var stars = lambda (n: Int) -> String: "*" * n
assert_equal(stars(histogram.get(5, 0)), "***")
assert_equal(stars(histogram.get(4, 0)), "****")
# --- FFI interop: a thin `abi("C")` lambda as a qsort comparator ---
def test_ffi_qsort() raises:
var values: List[Int] = [5, 3, 11, 10, 9, 6, 4]
var c_values: List[c_int] = transform(
lambda (v: Int) -> c_int: c_int(v), values
)
external_call["qsort", NoneType](
c_values.unsafe_ptr(),
c_size_t(len(c_values)),
c_size_t(size_of[c_int]()),
lambda (
a: MutOpaquePointer[MutUntrackedOrigin],
b: MutOpaquePointer[MutUntrackedOrigin],
) abi("C") -> c_int: a.unsafe_bitcast[c_int]()[]
- b.unsafe_bitcast[c_int]()[],
)
assert_equal(c_values, [3, 4, 5, 6, 9, 10, 11])
def main() raises:
test_creating_a_lambda()
test_bubble_sort_named_comparator()
test_bubble_sort_inline_lambda()
test_bubble_sort_flipped_comparison()
test_inplace_transform_thin_lambda()
test_closure_direct_call()
test_transform_capturing_lambda()
test_histogram()
test_ffi_qsort()
@@ -0,0 +1,687 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
# tests.mojo
# Tests for functions.mdx code examples.
#
# Not tested (intentional): the page's 13 `no-test` blocks are negative or
# illustrative examples -- undefined placeholder types, two spellings of one
# signature shown as equivalent, bodyless sketches, unsupported syntax, and
# deliberate compile errors. A runtime test can't assert a compile error.
#
# Reconciled to coexist in one module:
# - `my_pow()` is defined once, under `optional-args`. The page repeats the
# declaration under "Keyword arguments" so that example reads on its own;
# that block is tagged `duplicate-of=optional-args` in the MDX.
# - The page's two `make_worldly()` bodies are named `make_worldly()` and
# `make_worldly2()`, since one module can't define the same signature
# twice.
# - "Anatomy of a function" uses `max()`; `add()` belongs to the overload
# set under "Overloaded functions".
#
# `main()` is deliberately not `raises`: the `count-many-things` doc block
# shows a plain `def main():`. Assertions run through `run_tests()`, which
# catches and exits nonzero so a failure still fails the binary.
from std.collections import StringDict
from std.sys import exit
from std.testing import assert_equal, assert_raises
# --- Anatomy of a function ---
# start-do-nothing
def do_nothing():
pass
# end-do-nothing
# start-max-args
def max(a: Int, b: Int) -> Int:
return a if a > b else b
# end-max-args
def test_positional_arguments() raises:
assert_equal(max(5, 7), 7)
def test_keyword_arguments_in_any_order() raises:
assert_equal(max(b=3, a=9), 9)
assert_equal(max(a=9, b=3), 9)
def test_positional_and_keyword_arguments_mixed() raises:
assert_equal(max(5, b=7), 7)
def test_pass_body_is_a_complete_definition() raises:
do_nothing()
def greet_implicit(name: String):
pass
def greet_none(name: String) -> None:
pass
def test_omitted_and_explicit_none_return_types_are_equivalent() raises:
greet_implicit("Sam")
greet_none("Sam")
# --- Optional arguments ---
# start-optional-args
def my_pow(base: Int, exp: Int = 2) -> Int:
return base**exp
def use_defaults():
# Uses the default value for `exp`
var z = my_pow(3)
print(z)
# end-optional-args
def test_omitted_argument_uses_its_default() raises:
assert_equal(my_pow(3), 9)
def test_supplied_argument_overrides_the_default() raises:
assert_equal(my_pow(3, 3), 27)
# --- Keyword arguments ---
# start-keyword-args
def use_keywords():
# Uses keyword argument names (with order reversed)
var z = my_pow(exp=3, base=2)
print(z)
# end-keyword-args
def test_keyword_arguments_may_be_reordered() raises:
assert_equal(my_pow(exp=3, base=2), 8)
assert_equal(my_pow(base=2, exp=3), 8)
def test_keyword_form_matches_the_positional_form() raises:
assert_equal(my_pow(exp=3, base=2), my_pow(2, 3))
# --- Homogeneous variadic arguments ---
# start-variadic-greet
def greet(*names: String):
...
# end-variadic-greet
# start-variadic-sum
def sum(*values: Int) -> Int:
var sum: Int = 0
for value in values:
sum = sum + value
return sum
# end-variadic-sum
def test_sum_of_several_values() raises:
assert_equal(sum(1, 2, 3), 6)
def test_variadic_accepts_any_number_of_arguments() raises:
assert_equal(sum(), 0)
assert_equal(sum(7), 7)
assert_equal(sum(1, 2, 3, 4, 5), 15)
def test_greet_accepts_any_number_of_names() raises:
greet()
greet("Alice")
greet("Alice", "Bob")
def list_len(values: VariadicList[Int, _]) -> Int:
return len(values)
def variadic_list_len(*values: Int) -> Int:
return list_len(values)
def after_label(label: String, *values: Int) -> Int:
return list_len(values)
def test_variadic_argument_is_a_variadic_list() raises:
# Binding the argument to a `VariadicList` parameter stops compiling if
# the manual's claim about the in-function type ever goes stale.
assert_equal(variadic_list_len(1, 2, 3), 3)
def test_arguments_may_precede_the_variadic_argument() raises:
assert_equal(after_label("count", 1, 2), 2)
assert_equal(after_label("count"), 0)
# --- Mutating a variadic argument ---
# start-variadic-mut-ref
def make_worldly(mut *strs: String):
for ref i in strs:
i += " world"
# end-variadic-mut-ref
# start-variadic-mut-index
def make_worldly2(mut *strs: String):
for i in range(len(strs)):
strs[i] += " world"
# end-variadic-mut-index
def test_ref_binding_mutates_the_callers_values() raises:
var a = String("hello")
var b = String("hi")
make_worldly(a, b)
assert_equal(a, "hello world")
assert_equal(b, "hi world")
def test_indexing_mutates_the_callers_values() raises:
var a = String("hello")
var b = String("hi")
make_worldly2(a, b)
assert_equal(a, "hello world")
assert_equal(b, "hi world")
# --- Variadic keyword arguments ---
# start-print-nicely
def print_nicely(var **kwargs: Int):
for item in kwargs.items():
print(item.key, "=", item.value)
# end-print-nicely
def int_kwargs(var **kwargs: Int) -> StringDict[Int]:
return kwargs^
def float_kwargs(var **kwargs: Float64) -> StringDict[Float64]:
return kwargs^
def test_argument_dictionary_holds_the_passed_keywords() raises:
var kwargs = int_kwargs(a=7, y=8)
assert_equal(len(kwargs), 2)
assert_equal(kwargs["a"], 7)
assert_equal(kwargs["y"], 8)
def test_argument_dictionary_type_follows_the_argument_type() raises:
# Both return annotations stop compiling if the dictionary is no longer a
# `StringDict` of the declared argument type.
assert_equal(float_kwargs(x=1.5)["x"], 1.5)
def test_any_number_of_keyword_arguments() raises:
print_nicely()
print_nicely(a=7, y=8)
# --- Positional-only and keyword-only arguments ---
# start-positional-only
def min(a: Int, b: Int, /) -> Int:
return a if a < b else b
# end-positional-only
# start-keyword-only-after-variadic
def sort(*values: Float64, ascending: Bool = True):
...
# end-keyword-only-after-variadic
# start-keyword-only
def kw_only_args(a1: Int, a2: Int, *, double: Bool) -> Int:
var product = a1 * a2
if double:
return product * 2
else:
return product
# end-keyword-only
def test_positional_only_arguments() raises:
assert_equal(min(1, 2), 1)
assert_equal(min(2, 1), 1)
assert_equal(min(3, 3), 3)
def test_required_keyword_only_argument() raises:
assert_equal(kw_only_args(2, 3, double=True), 12)
assert_equal(kw_only_args(2, 3, double=False), 6)
def test_keyword_only_argument_after_a_variadic_is_optional() raises:
sort(1.1, 6.5, 4.3)
sort(1.1, 6.5, 4.3, ascending=False)
sort(ascending=True)
# --- Overloaded functions ---
# start-overloaded-add
def add(x: Int, y: Int) -> Int:
return x + y
def add(x: String, y: String) -> String:
return x + y
# end-overloaded-add
def test_int_overload() raises:
assert_equal(add(2, 3), 5)
def test_string_overload() raises:
assert_equal(add(String("Hello, "), String("world")), "Hello, world")
def test_string_literal_reaches_the_string_overload() raises:
# A `StringLiteral` converts implicitly to `String`, which also has to
# select the `String` overload over the `Int` one.
assert_equal(add("Hello, ", "world"), "Hello, world")
# --- Overload resolution: ambiguity resolved by an explicit cast ---
# start-overload-ambiguity
struct MyString:
@implicit
def __init__(out self, string: String):
pass
struct YourString:
@implicit
def __init__(out self, string: String):
pass
def foo(name: MyString):
print("MyString")
def foo(name: YourString):
print("YourString")
def call_foo():
# Both `foo` overloads can accept `"Hello"`, so Mojo doesn't know
# which one to call.
foo(MyString("Hello"))
# end-overload-ambiguity
def which(name: MyString) -> String:
return "MyString"
def which(name: YourString) -> String:
return "YourString"
def test_explicit_cast_selects_the_intended_overload() raises:
# The manual's `foo()` overloads print instead of returning, so these
# mirror them over the same two types to make the choice observable.
assert_equal(which(MyString("Hello")), "MyString")
assert_equal(which(YourString("Hello")), "YourString")
# --- Overload resolution: the precedence rules ---
struct Wrapper:
@implicit
def __init__(out self, value: Int):
pass
def fewest_conversions(x: Int) -> String:
return "exact"
def fewest_conversions(x: Wrapper) -> String:
return "converted"
def test_fewest_implicit_conversions_wins() raises:
assert_equal(fewest_conversions(1), "exact")
def no_variadic(x: Int) -> String:
return "non-variadic"
def no_variadic(*x: Int) -> String:
return "variadic"
def test_candidate_without_variadic_arguments_wins() raises:
assert_equal(no_variadic(1), "non-variadic")
def shortest_signature(x: Int) -> String:
return "no-parameters"
def shortest_signature[T: Intable](x: T) -> String:
return "one-parameter"
def test_shortest_parameter_signature_wins() raises:
assert_equal(shortest_signature(1), "no-parameters")
@fieldwise_init
struct OverloadedStruct:
def foo(self) -> String:
return "instance"
@staticmethod
def foo() -> String:
return "static"
def test_non_staticmethod_candidate_wins() raises:
var instance = OverloadedStruct()
assert_equal(instance.foo(), "instance")
# Calling on an rvalue, `OverloadedStruct().foo()`, currently selects the
# static overload instead. Known compiler bug, deliberately not asserted.
# --- Return values ---
# start-get-greeting
def get_greeting() -> String:
return "Hello"
# end-get-greeting
def test_string_literal_converts_to_the_declared_return_type() raises:
assert_equal(get_greeting(), "Hello")
# --- Named results ---
@fieldwise_init
struct NameTag:
var name: String
# start-named-result
def get_name_tag(var name: String, out name_tag: NameTag):
name_tag = NameTag(name^)
# end-named-result
def tag_out_first(out tag: NameTag, var name: String):
tag = NameTag(name^)
def tag_bare_return(var name: String, out tag: NameTag):
tag = NameTag(name^)
return
def tag_returns_a_value(var name: String, out tag: NameTag):
tag = NameTag(String("ignored"))
return NameTag(name^)
def test_named_result_reaches_the_caller() raises:
assert_equal(get_name_tag("Judith").name, "Judith")
def test_out_argument_may_appear_first() raises:
assert_equal(tag_out_first(name="Judith").name, "Judith")
def test_bare_return_yields_the_out_argument() raises:
assert_equal(tag_bare_return("Judith").name, "Judith")
def test_returned_value_wins_over_the_out_argument() raises:
# The `out` argument is initialized to something else first, so this only
# passes if the explicit `return` value is what reaches the caller.
assert_equal(tag_returns_a_value("Judith").name, "Judith")
# --- Named results: returning a type that can't be moved or copied ---
# start-immovable-object
struct ImmovableObject:
var name: String
def __init__(out self, var name: String):
self.name = name^
def create_immovable_object(var name: String, out obj: ImmovableObject):
obj = ImmovableObject(name^)
obj.name += "!"
# obj is implicitly returned
# end-immovable-object
# start-immovable-direct-return
def create_immovable_object3(var name: String) -> ImmovableObject:
return ImmovableObject(name^) # OK
# end-immovable-direct-return
def test_named_result_is_built_in_place() raises:
assert_equal(create_immovable_object("Blob").name, "Blob!")
def test_value_returned_immediately_needs_no_move() raises:
assert_equal(create_immovable_object3("Bob").name, "Bob")
# --- Raising and non-raising functions ---
# start-raises-error
def raises_error() raises:
raise Error("There was an error.")
# end-raises-error
# The page shows these alongside a third function that deliberately fails to
# compile, so the block is marked `no-test` and only these two are here.
def handle_error():
try:
raises_error()
except e:
print("Handled an error:", e)
def propagate_error() raises:
raises_error()
def test_raises_error_propagates_its_message() raises:
with assert_raises(contains="There was an error."):
raises_error()
def test_handle_error_swallows_the_error() raises:
handle_error()
def test_propagate_error_re_raises_to_its_caller() raises:
with assert_raises(contains="There was an error."):
propagate_error()
# --- Test runner ---
def run_tests():
try:
test_positional_arguments()
test_keyword_arguments_in_any_order()
test_positional_and_keyword_arguments_mixed()
test_pass_body_is_a_complete_definition()
test_omitted_and_explicit_none_return_types_are_equivalent()
test_omitted_argument_uses_its_default()
test_supplied_argument_overrides_the_default()
test_keyword_arguments_may_be_reordered()
test_keyword_form_matches_the_positional_form()
test_sum_of_several_values()
test_variadic_accepts_any_number_of_arguments()
test_greet_accepts_any_number_of_names()
test_variadic_argument_is_a_variadic_list()
test_arguments_may_precede_the_variadic_argument()
test_ref_binding_mutates_the_callers_values()
test_indexing_mutates_the_callers_values()
test_argument_dictionary_holds_the_passed_keywords()
test_argument_dictionary_type_follows_the_argument_type()
test_any_number_of_keyword_arguments()
test_positional_only_arguments()
test_required_keyword_only_argument()
test_keyword_only_argument_after_a_variadic_is_optional()
test_int_overload()
test_string_overload()
test_string_literal_reaches_the_string_overload()
test_explicit_cast_selects_the_intended_overload()
test_fewest_implicit_conversions_wins()
test_candidate_without_variadic_arguments_wins()
test_shortest_parameter_signature_wins()
test_non_staticmethod_candidate_wins()
test_string_literal_converts_to_the_declared_return_type()
test_named_result_reaches_the_caller()
test_out_argument_may_appear_first()
test_bare_return_yields_the_out_argument()
test_returned_value_wins_over_the_out_argument()
test_named_result_is_built_in_place()
test_value_returned_immediately_needs_no_move()
test_raises_error_propagates_its_message()
test_handle_error_swallows_the_error()
test_propagate_error_re_raises_to_its_caller()
test_documented_result()
test_int_conversion_truncates()
test_pack_accepts_any_number_of_arguments()
except e:
print("test failure:", e)
exit(1)
# --- Heterogeneous variadic arguments ---
#
# `count_many_things()` must stay the last definition in this file. Its doc
# region runs from the `def` through `main()`'s first statement, so nothing
# may come between them.
def test_documented_result() raises:
# The manual annotates this call with `# 28`.
assert_equal(count_many_things(5, 11.7, 12), 28)
def test_int_conversion_truncates() raises:
assert_equal(count_many_things(11.7), 11)
def test_pack_accepts_any_number_of_arguments() raises:
assert_equal(count_many_things(), 0)
assert_equal(count_many_things(1), 1)
# start-count-many-things
def count_many_things[*ArgTypes: Intable](*args: *ArgTypes) -> Int:
var total = 0
comptime for i in range(args.__len__()):
total += Int(args[i])
return total
def main():
print(count_many_things(5, 11.7, 12)) # 28
# end-count-many-things
# start-arg-passing
# positional
var x = max(5, 7) # Positionally, a=5 and b=7
# keyword
var y = max(b=3, a=9)
# mixed
var z = max(5, b=7) # Positionally, a=5
# end-arg-passing
print(x, y, z)
# start-print-nicely-call
# prints:
# `a = 7`
# `y = 8`
print_nicely(a=7, y=8)
# end-print-nicely-call
# start-sort-call
sort(1.1, 6.5, 4.3, ascending=False)
# end-sort-call
# start-named-result-call
var tag = get_name_tag("Judith")
# end-named-result-call
print(tag.name)
# start-immovable-object-call
var my_obj = create_immovable_object("Blob")
# end-immovable-object-call
print(my_obj.name)
do_nothing()
use_defaults()
use_keywords()
greet("Alice", "Bob")
print(sum(1, 2, 3))
print(add(2, 3))
print(get_greeting())
print(create_immovable_object3("Bob").name)
call_foo()
handle_error()
run_tests()
@@ -0,0 +1,479 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
# tests.mojo
# Tests for generics.mdx code examples.
#
# Compile-only (no runtime assertions, exercised by main()):
# - my_parameterized_fn, the `Some` function-type and variadic before/after
# pairs, the Foo composition struct, and the fixed/dynamic
# value-vs-argument examples are signature-only on the page; main()
# calls them to confirm they build.
#
# Not tested (intentional):
# - The erroring `function` that prints an `AnyType` directly, the
# `Some` struct field that can't infer a concrete type, and the
# zero-capacity SizedListWrapper are negative examples on the page.
# - The prose-only section ("Parameterized declarations and
# explicit destruction") has no code.
#
# Renamed to coexist in one file (the page names both `Pair`):
# - Parameterized types -> `Pair`; parts conformance -> `HashablePair`.
from std.testing import assert_equal, assert_false, assert_true
from std.sys.info import is_64bit
# --- Intro: value parameter alongside a type parameter ---
# The page bounds `T` as `Comparable & ImplicitlyCopyable & Deinitable`
# so the compile-time `threshold` value can be used in the runtime comparison.
def count_above[
T: Comparable & ImplicitlyCopyable & Deinitable, threshold: T
](values: List[T]) -> Int:
var count = 0
for v in values:
if v > threshold:
count += 1
return count
def test_count_above() raises:
assert_equal(count_above[Int, 3]([1, 2, 3, 4, 5]), 2)
# --- Basic parameterized declarations: compare two lists ---
def all_equal_int(ref lhs: List[Int], ref rhs: List[Int]) -> Bool:
if len(lhs) != len(rhs):
return False
for left, right in zip(lhs, rhs):
if left != right:
return False
return True
def all_equal[
T: Equatable & Copyable & Deinitable
](ref lhs: List[T], ref rhs: List[T]) -> Bool:
if len(lhs) != len(rhs):
return False
for left, right in zip(lhs, rhs):
if left != right:
return False
return True
def test_all_equal() raises:
assert_true(all_equal_int([1, 2, 3], [1, 2, 3]))
assert_false(all_equal_int([1, 2, 3], [4, 5, 6]))
# The compiler infers T from each call site.
assert_true(all_equal([1, 2, 3], [1, 2, 3]))
assert_false(all_equal([1, 2, 3], [4, 5, 6]))
assert_true(all_equal(["hello", "world"], ["hello", "world"]))
assert_false(all_equal(["hello", "world"], ["goodbye", "world"]))
# --- Parameterized types: AnyType (compile-only) ---
def my_parameterized_fn[T: AnyType](value: T):
pass
# --- Printing under-specified parameterized values ---
@fieldwise_init
struct SomeStruct:
var x: Int
def represent[T: AnyType](v: T) -> String:
comptime if conforms_to(T, Writable):
return String(v)
else:
return String(t"{reflect[T].name()}")
def function[Ts: AnyType](*args: Ts) raises:
for arg in args:
assert_true(represent(arg).byte_length() > 0)
def test_printing_under_specified_values() raises:
function(1, 2, 3)
function(SomeStruct(1), SomeStruct(2))
# --- Simplified conformance with `Some`: arguments ---
def as_int_param[T: Intable, //](x: T) -> Int:
return x.__int__()
def as_int_some(x: Some[Intable]) -> Int:
return x.__int__()
def test_some_arguments() raises:
assert_equal(as_int_param(42.1), 42)
assert_equal(as_int_some(42.1), 42)
# --- Simplified conformance with `Some`: function types (compile-only) ---
def sync_parallelize_param[
FuncType: def(Int) -> None,
](func: FuncType):
pass
def sync_parallelize_some(func: Some[def(Int) -> None]):
pass
def int_to_none(x: Int) -> None:
pass
# --- Simplified conformance with `Some`: variadics (compile-only) ---
def show_param[*Ts: Writable](*pack: *Ts):
pass
def show_some(*pack: *SomeTypeList[Writable]):
pass
# --- Simplified conformance with `Some`: operator overloads ---
@fieldwise_init
struct IndexParam[T: Copyable & Deinitable]:
var x: Self.T
def __getitem__[I: Indexer, //](self, idx: I) -> ref[self.x] Self.T:
return self.x
@fieldwise_init
struct IndexSome[T: Copyable & Deinitable]:
var x: Self.T
def __getitem__(self, idx: Some[Indexer]) -> ref[self.x] Self.T:
return self.x
def test_some_operator_overloads() raises:
assert_equal(IndexParam(42)[0], 42)
assert_equal(IndexSome(42)[0], 42)
# --- Where `Some` won't work: move conformance back to a type parameter ---
# The page names this `Struct`; the broken `Some` field version that
# precedes it is a negative example (it can't infer a concrete type).
@fieldwise_init
struct FixedStruct[T: Copyable & Deinitable & Writable](Writable):
var x: Self.T
def test_where_some_wont_work() raises:
var s = FixedStruct(1)
assert_true("1" in String(s)) # FixedStruct[Int](x=1)
# --- Parameterized types ---
comptime ComparableValue = Equatable & ImplicitlyCopyable & Deinitable
@fieldwise_init
struct Pair[T: ComparableValue](ComparableValue):
var left: Self.T
var right: Self.T
def __eq__(self, other: Pair[Self.T]) -> Bool:
return self.left == other.left and self.right == other.right
def test_parameterized_types() raises:
assert_true(Pair(1, 2) == Pair(1, 2))
assert_false(Pair(1, 2) == Pair(1, 3))
# --- Mixing type and value parameters ---
struct ExampleStruct:
def __init__(out self):
pass
def example[
T: Writable & Copyable, # type parameter
count: Int, # value parameter
](
self,
data: String, # argument
init_value: T, # generic argument
) -> String:
var result = String(data)
for _ in range(count):
result += String(init_value)
return result
def test_mixing_type_and_value() raises:
assert_equal(ExampleStruct().example[Int, 3]("x:", 7), "x:777")
# --- Type refinement: `conforms_to` ---
# The page prints the result; this returns a String so it can be asserted.
def process[T: AnyType](value: T) -> String:
comptime if conforms_to(T, Writable & ImplicitlyCopyable & Deinitable):
return String(value)
else:
return "<not writable>"
def test_type_refinement() raises:
assert_equal(process(42), "42")
assert_equal(process("Hello, Mojo!"), "Hello, Mojo!")
assert_equal(process(3.14), "3.14")
assert_equal(process([1, 2, 3]), "<not writable>")
assert_equal(process({"key": "value"}), "<not writable>")
# --- Value parameters: basic example ---
comptime MyCollectionElement = ImplicitlyCopyable & Deinitable
def make_filled[T: MyCollectionElement, size: Int](splat_value: T) -> List[T]:
var result = List[T](capacity=size)
for _ in range(size):
result.append(splat_value)
return result^
def test_make_filled() raises:
var three_zeros = make_filled[Int, 3](0)
var five_hellos = make_filled[String, 5]("hello")
assert_equal(three_zeros, [0, 0, 0])
assert_equal(five_hellos, ["hello", "hello", "hello", "hello", "hello"])
# --- Value parameters vs runtime arguments (compile-only) ---
def fixed[size: Int]():
var buf = Array[Int, size](fill=0)
_ = buf
def dynamic(size: Int):
var buf = List[Int](capacity=size)
_ = buf
# --- Conditional trait conformance: derived conformance and method access ---
# This single `Wrapper` combines the page's "derived conformance" example
# (conditional `Writable`) and its "conditional method access" example
# (conditional `Boolable` gating `__bool__()`).
comptime BaseTraits = Copyable & Deinitable
@fieldwise_init
struct Wrapper[T: BaseTraits](
Boolable where conforms_to(T, Boolable),
Writable where conforms_to(T, Writable),
):
var value: Self.T
def __bool__(self) -> Bool where conforms_to(Self.T, Boolable):
return self.value.__bool__()
@fieldwise_init
struct NotWritable(BaseTraits):
var data: Int
def test_conditional_conformance() raises:
# Int and String are Writable, so Wrapper gains Writable.
var w_int = Wrapper[Int](42)
assert_true("42" in String(w_int))
var w_str = Wrapper[String]("Hello")
assert_true("Hello" in String(w_str))
# Boolable gates __bool__(): non-empty is truthy, empty is falsy.
assert_true(Bool(w_str))
var w_empty_str = Wrapper[String]("")
assert_false(Bool(w_empty_str))
# NotWritable wrappers are constructible but gain neither conformance.
var w_not_writable = Wrapper[NotWritable](NotWritable(10))
_ = w_not_writable
# --- Conditional trait conformance: parts conformance ---
# The page names this `Pair`; renamed here to coexist with the parameterized
# `Pair` from the "Parameterized types" section.
@fieldwise_init
struct HashablePair[L: BaseTraits, R: BaseTraits](
Hashable where conforms_to(L, Hashable) and conforms_to(R, Hashable)
):
var left: Self.L
var right: Self.R
@fieldwise_init
struct NotHashable(BaseTraits):
var data: Int
def test_parts_conformance() raises:
# Both parts are Hashable, so the pair gains hash().
var pair = HashablePair[Int, String](left=1, right="one")
_ = hash(pair)
# Constructible, but hashing is unavailable when a part isn't Hashable.
var pair2 = HashablePair[Int, NotHashable](left=1, right=NotHashable(10))
_ = pair2
# --- Conditional trait composition (compile-only) ---
@fieldwise_init
struct Foo[T: AnyType](Copyable, Writable where conforms_to(T, Writable)):
pass
# --- Conditional conformance with value parameters ---
# The page bounds `T` as `Writable & Copyable & Deinitable` (via the
# `ElementTraits` alias) so `write_to()` type-checks; the conditional behavior
# demonstrated here is the value condition `capacity > 0`.
struct SizedListWrapper[capacity: Int, T: Writable & Copyable & Deinitable](
Sized, Writable where conforms_to(T, Writable) and capacity > 0
):
var data: List[Self.T]
def __init__(out self, value: Self.T):
self.data = List[Self.T](capacity=Self.capacity)
for _ in range(Self.capacity):
self.data.append(value.copy())
def __len__(self) -> Int:
return len(self.data)
def write_to(self, mut writer: Some[Writer]):
writer.write(repr(self.data))
def first(self) -> Self.T where Self.capacity > 0:
return self.data[0].copy()
def test_value_param_conformance() raises:
var s = SizedListWrapper[5, Int](42)
assert_equal(len(s), 5)
assert_equal(s.first(), 42)
assert_true(conforms_to(type_of(s), Writable))
# Gate a function on a trait with a where clause.
def describe[T: AnyType](value: T) -> String where conforms_to(T, Writable):
return String(value)
# Combine checks with `and`.
def describe_copyable[
T: AnyType
](value: T) -> String where conforms_to(T, Writable) and conforms_to(
T, Copyable
):
return String(value)
# A numeric fact on a parameter: a power-of-two width.
def block[w: Int]() -> Int where w.is_power_of_two():
return w
# A DType kind predicate on a parameter.
def float_only[dt: DType]() -> Bool where dt.is_floating_point():
return True
def test_where_clauses() raises:
assert_equal(describe(2), "2") # Int is Writable
assert_equal(describe("hello"), "hello") # String is Writable
assert_equal(describe_copyable(7), "7") # Writable and Copyable
assert_equal(block[8](), 8) # 8 is a power of two
assert_true(float_only[DType.float32]()) # float32 is floating point
# process(non_writable) would be a COMPILE error (fails the where);
# a runtime test can't assert a compile error.
# Contrast: is_64bit() works in `comptime if`, NOT in a `where` clause.
def test_comptime_if_machine() raises:
var w: Int
comptime if is_64bit():
w = 64
else:
w = 32
assert_equal(w, 64)
def main() raises:
test_count_above()
test_all_equal()
test_printing_under_specified_values()
test_some_arguments()
test_some_operator_overloads()
test_where_some_wont_work()
test_parameterized_types()
test_mixing_type_and_value()
test_type_refinement()
test_make_filled()
test_conditional_conformance()
test_parts_conformance()
test_value_param_conformance()
test_where_clauses()
test_comptime_if_machine()
# Compile-only examples: confirm the signature-only snippets build.
my_parameterized_fn(42)
sync_parallelize_param(int_to_none)
sync_parallelize_some(int_to_none)
show_param(1, 2, 3)
show_some(1, 2, 3)
fixed[4]()
dynamic(4)
_ = Foo[Int]()
@@ -0,0 +1,530 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
# tests.mojo
# Tests for get-started.mdx code examples.
#
# get-started.mdx is the source of truth. Every snippet here is copied
# from that page, including the finished `Grid`, so this file stands
# alone. When the page changes, this file has to change with it, and it
# fails the build when the page's code stops working.
#
# Not tested (no runnable behavior to assert from this file):
# - `print_grid()` output itself (writes to stdout). The rendering rule
# is pinned instead by `render()` below, which is the same loop
# accumulating into a `String`.
# - splitting `Grid` into its own `grid.mojo` and importing it, which is
# a source-layout step with no runtime behavior
# - `seed()` producing distinct runs, and the specific cells
# `random_grid()` fills (random); only its invariants are asserted
# - the `main()` animation loop: ANSI escape codes, `sleep()`, and the
# generation loop have no assertable result
#
# The page's raising `__getitem__()` is shown and then reverted, so the
# `Grid` below keeps the plain getter. That snippet is reproduced further
# down rather than left untested.
from std.random import random_si64, seed
from std.testing import assert_equal, assert_false, assert_raises, assert_true
# --- The finished `Grid`, as the page's "Final code" section shows it ---
struct Grid[num_cols: Int, num_rows: Int]:
var cells: List[Int] # Holds the current generation
var next_cells: List[Int] # Holds the next generation
var count: Int
def __init__(out self):
self.count = Self.num_cols * Self.num_rows
self.cells = List[Int](length=self.count, fill=0)
self.next_cells = List[Int](length=self.count, fill=0)
comptime to_index = lambda (x: Int, y: Int) -> Int: (y * Self.num_cols + x)
comptime to_coord = lambda (i: Int) -> Tuple[Int, Int]: (
(i % Self.num_cols, i // Self.num_cols)
)
def print_grid(self):
var grid_str = "".join(
[
(
("X" if value else ".")
+ ("\n" if (index + 1) % Self.num_cols == 0 else "")
)
for index, value in enumerate(self.cells)
]
)
print(grid_str)
# var grid_str = ""
# for index in range(len(self.cells)):
# grid_str += "X" if self.cells[index] else "."
# if (
# index % Self.num_cols == (Self.num_cols - 1)
# and index != len(self.cells) - 1
# ):
# grid_str += "\n"
# print(grid_str)
def is_valid_coord(self, coord: Tuple[Int, Int]) -> Bool:
return not (
coord[0] < 0
or coord[0] >= Self.num_cols
or coord[1] < 0
or coord[1] >= Self.num_rows
)
def __setitem__(mut self, coord: Tuple[Int, Int], value: Int):
if not self.is_valid_coord(coord):
return # no op
self.cells[Self.to_index(coord[0], coord[1])] = value
def __getitem__(self, coord: Tuple[Int, Int]) -> Int:
return self.cells[Self.to_index(coord[0], coord[1])]
@staticmethod
def random_grid(clumps: Int = 2) -> Self:
var grid = Self()
for _ in range(clumps):
var idx = Int(random_si64(0, Int64(grid.count) - 1))
var x, y = Self.to_coord(idx)
grid[(x, y)] = 1 # Fill index cell
for dx in range(-1, 2): # -1, 0, or 1
for dy in range(-1, 2):
if not grid.is_valid_coord((x + dx, y + dy)):
continue
if random_si64(0, 3) > 0:
continue # 75% skip
grid[(x + dx, y + dy)] = 1
return grid^
def evolve_cell(mut self, i: Int):
var is_live = Bool(self.cells[i])
self.next_cells[i] = 0
# Count the neighbors
var ncount = -1 if is_live else 0 # Exclude self from the count
var x, y = Self.to_coord(i)
for dx in range(-1, 2):
for dy in range(-1, 2):
var nx = x + dx
var ny = y + dy
ncount += self.cells[Self.to_index(nx, ny)]
# Live cell stays alive with two or three live neighbors
if is_live and (ncount == 2 or ncount == 3):
self.next_cells[i] = 1
# Inactive cell becomes alive with exactly three live neighbors
elif not is_live and ncount == 3:
self.next_cells[i] = 1
def evolve(mut self):
for i in range(self.count):
var x, y = Self.to_coord(i)
# Edges are excluded from evolution and will always go inactive.
if (
x == 0
or y == 0
or x == Self.num_cols - 1
or y == Self.num_rows - 1
):
self.next_cells[i] = 0 # Edges go inactive
continue
self.evolve_cell(i)
# Swap the current and next cell states
var tmp = self.cells^ # Transfer
self.cells = self.next_cells^ # Transfer
self.next_cells = tmp^ # Every cell is written, so this is safe
# --- Helper: the `print_grid()` loop, accumulating instead of printing ---
def render(cells: List[Int], num_cols: Int) -> String:
var out = String()
for index in range(len(cells)):
out += "X" if cells[index] else "."
if index % num_cols == (num_cols - 1):
out += "\n"
return out
# The grid the tutorial prints in its first two steps.
comptime GLIDER_8X8 = String(
"..X.....\n"
"X.X.....\n"
".XX.....\n"
"........\n"
"........\n"
"........\n"
"........\n"
"........\n"
)
# --- Game state: a list, a lambda, and tuple coordinates ---
def test_glider_grid() raises:
var count: Int = 64
var num_cols: Int = 8
var glider_grid: List[Int] = List[Int](length=64, fill=0)
# Convert (x, y) coordinates to a linear index in the grid
var to_index = lambda (x: Int, y: Int) -> Int: y * num_cols + x
for coord in [(0, 1), (1, 2), (2, 0), (2, 1), (2, 2)]:
glider_grid[to_index(coord[0], coord[1])] = 1
assert_equal(count, 64)
assert_equal(len(glider_grid), 64)
# The five glider cells, and only those, are live.
assert_equal(render(glider_grid, num_cols), GLIDER_8X8)
var live = 0
for index in range(count):
live += glider_grid[index]
assert_equal(live, 5)
def test_to_index_lambda() raises:
var num_cols = 8
var to_index = lambda (x: Int, y: Int) -> Int: y * num_cols + x
# x is the column, y is the row.
assert_equal(to_index(0, 0), 0)
assert_equal(to_index(2, 0), 2)
assert_equal(to_index(0, 1), 8)
assert_equal(to_index(7, 7), 63)
def test_list_expression() raises:
var values: List[Int] = [12, -7, 64] # This is a list expression
assert_equal(len(values), 3)
assert_equal(values[0], 12)
assert_equal(values[1], -7)
assert_equal(values[2], 64)
def test_tuple_mixed_types() raises:
# Tuples have a fixed number of elements and can contain different types.
var pair = (0, 1)
assert_equal(pair[0], 0)
assert_equal(pair[1], 1)
var mixed = (1, "two", 3.0)
assert_equal(mixed[0], 1)
assert_equal(mixed[1], "two")
assert_equal(mixed[2], 3.0)
# --- Add reusable printing: the display loop moved into a function ---
def print_grid(grid: List[Int], num_cols: Int):
for index in range(len(grid)):
print("X" if grid[index] else ".", end="")
if index % num_cols == (num_cols - 1):
print()
def test_print_grid_runs() raises:
# `print_grid()` writes to stdout, so this only checks that the
# extracted function compiles and runs over the tutorial's grid.
var glider_grid: List[Int] = List[Int](length=64, fill=0)
for coord in [(0, 1), (1, 2), (2, 0), (2, 1), (2, 2)]:
glider_grid[coord[1] * 8 + coord[0]] = 1
print_grid(glider_grid, 8)
# --- Add lookups: the constants and conversions hoisted to `comptime` ---
comptime count: Int = 64
comptime num_cols: Int = 8
comptime to_index = lambda (x: Int, y: Int) -> Int: (y * num_cols + x)
comptime to_coord = lambda (i: Int) -> Tuple[Int, Int]: (
(i % num_cols, i // num_cols)
)
def test_comptime_constants() raises:
assert_equal(count, 64)
assert_equal(num_cols, 8)
def test_integer_division_operators() raises:
# `//` rounds towards negative infinity; `/` on `Int` returns an `Int`,
# rounding towards zero. The operands have to be typed for that to hold:
# untyped literals infer a float, so an unannotated `count / num_cols`
# is 8.0. Annotating the result doesn't recover it, so the page declares
# the constants as `Int`.
assert_equal(count // num_cols, 8)
assert_equal(count / num_cols, 8)
var seven: Int = 7
var two: Int = 2
assert_equal(seven // two, 3)
assert_equal(-seven // two, -4)
assert_equal(seven / two, 3)
assert_equal(-seven / two, -3)
def test_comptime_conversions() raises:
assert_equal(to_index(0, 1), 8)
assert_equal(to_index(2, 2), 18)
# The declared `Tuple[Int, Int]` return type converts `i // num_cols`
# back to an `Int`, truncating toward negative infinity.
var x, y = to_coord(18)
assert_equal(x, 2)
assert_equal(y, 2)
var last_x, last_y = to_coord(63)
assert_equal(last_x, 7)
assert_equal(last_y, 7)
# Every index round-trips through both directions.
for i in range(count):
var cx, cy = to_coord(i)
assert_equal(to_index(cx, cy), i)
def test_comptime_grid_setup() raises:
var glider_grid: List[Int] = List[Int](length=64, fill=0)
for coord in [(0, 1), (1, 2), (2, 0), (2, 1), (2, 2)]:
glider_grid[to_index(coord[0], coord[1])] = 1
assert_equal(render(glider_grid, num_cols), GLIDER_8X8)
# --- Define a `Grid` type: parameters size the instance ---
def test_grid_init() raises:
var glider_grid = Grid[8, 8]()
assert_equal(glider_grid.count, 64)
assert_equal(len(glider_grid.cells), 64)
# Every field is set before the initializer returns; cells start
# inactive.
for index in range(glider_grid.count):
assert_equal(glider_grid.cells[index], 0)
def test_grid_parameters() raises:
# `count` comes from the grid dimensions, so it tracks the parameters.
assert_equal(Grid[4, 6]().count, 24)
assert_equal(Grid[60, 20]().count, 1200)
# --- Add grid operations: indexing through `__getitem__`/`__setitem__` ---
def test_grid_indexing() raises:
var glider_grid = Grid[8, 8]()
glider_grid[(2, 1)] = 1
assert_equal(glider_grid[(2, 1)], 1)
# `Self.to_index()` puts (x, y) at y * num_cols + x.
assert_equal(glider_grid.cells[10], 1)
glider_grid[(2, 1)] = 0
assert_equal(glider_grid[(2, 1)], 0)
def test_grid_static_conversions() raises:
assert_equal(Grid[8, 8].to_index(2, 1), 10)
var x, y = Grid[8, 8].to_coord(10)
assert_equal(x, 2)
assert_equal(y, 1)
def test_grid_glider_setup() raises:
var glider_grid = Grid[8, 8]()
for coord in [(0, 1), (1, 2), (2, 0), (2, 1), (2, 2)]:
glider_grid[coord] = 1 # Uses indexing
assert_equal(render(glider_grid.cells, 8), GLIDER_8X8)
# --- Add protection: coordinates are checked before indexing ---
def test_is_valid_coord() raises:
var glider_grid = Grid[8, 8]()
assert_true(glider_grid.is_valid_coord((0, 0)))
assert_true(glider_grid.is_valid_coord((7, 7)))
assert_false(glider_grid.is_valid_coord((-1, 0)))
assert_false(glider_grid.is_valid_coord((0, -1)))
assert_false(glider_grid.is_valid_coord((8, 0)))
assert_false(glider_grid.is_valid_coord((0, 8)))
def test_setitem_out_of_bounds_is_a_no_op() raises:
var glider_grid = Grid[8, 8]()
glider_grid[(-1, 0)] = 1
glider_grid[(0, -1)] = 1
glider_grid[(8, 0)] = 1
glider_grid[(0, 8)] = 1
# Nothing was written, so no cell wrapped around into the grid.
for index in range(glider_grid.count):
assert_equal(glider_grid.cells[index], 0)
# --- Introducing errors: the raising getter the page shows, then reverts ---
def checked_get(grid: Grid[8, 8], coord: Tuple[Int, Int]) raises -> Int:
if not grid.is_valid_coord(coord):
raise String(t"Invalid coordinate: ({coord[0]}, {coord[1]})")
return grid[coord]
def test_checked_getitem() raises:
var grid = Grid[8, 8]()
grid[(2, 1)] = 1
assert_equal(checked_get(grid, (2, 1)), 1)
# Once the getter raises, every caller must raise or handle the error.
with assert_raises(contains="Invalid coordinate: (8, 0)"):
_ = checked_get(grid, (8, 0))
# --- Construct the random grid: only the invariants are deterministic ---
def test_random_grid_single_clump() raises:
seed()
# One clump is a center cell, always filled, plus up to its eight
# neighbors at 25% each.
var grid = Grid[8, 8].random_grid(1)
assert_equal(grid.count, 64)
var live = 0
for index in range(grid.count):
live += grid.cells[index]
assert_true(live >= 1)
assert_true(live <= 9)
def test_random_grid_no_clumps() raises:
seed()
# `for _ in range(clumps)` runs zero times, so the grid stays empty.
var grid = Grid[8, 8].random_grid(0)
for index in range(grid.count):
assert_equal(grid.cells[index], 0)
def test_random_grid_default_clumps() raises:
seed()
# The default is two clumps, at most nine cells each. They can land on
# top of each other, so only the upper bound is fixed.
var grid = Grid[8, 8].random_grid()
var live = 0
for index in range(grid.count):
live += grid.cells[index]
assert_true(live >= 1)
assert_true(live <= 18)
# --- Evolve: the three rules, applied to every interior cell ---
def test_evolve_still_life() raises:
# A 2 x 2 block has each of its cells at exactly three neighbors,
# so it survives unchanged.
var grid = Grid[8, 8]()
for coord in [(3, 3), (4, 3), (3, 4), (4, 4)]:
grid[coord] = 1
grid.evolve()
assert_equal(grid[(3, 3)], 1)
assert_equal(grid[(4, 3)], 1)
assert_equal(grid[(3, 4)], 1)
assert_equal(grid[(4, 4)], 1)
def test_evolve_blinker_oscillates() raises:
# A vertical blinker turns horizontal, then back.
var grid = Grid[8, 8]()
for coord in [(3, 2), (3, 3), (3, 4)]:
grid[coord] = 1
grid.evolve()
assert_equal(grid[(2, 3)], 1)
assert_equal(grid[(3, 3)], 1)
assert_equal(grid[(4, 3)], 1)
assert_equal(grid[(3, 2)], 0)
assert_equal(grid[(3, 4)], 0)
grid.evolve()
assert_equal(grid[(3, 2)], 1)
assert_equal(grid[(3, 3)], 1)
assert_equal(grid[(3, 4)], 1)
assert_equal(grid[(2, 3)], 0)
assert_equal(grid[(4, 3)], 0)
def test_evolve_underpopulation() raises:
# A lone live cell has no neighbors, so it goes inactive.
var grid = Grid[8, 8]()
grid[(3, 3)] = 1
grid.evolve()
assert_equal(grid[(3, 3)], 0)
def test_evolve_birth() raises:
# An inactive cell with exactly three live neighbors becomes alive.
var grid = Grid[8, 8]()
for coord in [(3, 2), (4, 2), (3, 3)]:
grid[coord] = 1
assert_equal(grid[(4, 3)], 0)
grid.evolve()
assert_equal(grid[(4, 3)], 1)
def test_evolve_edges_go_inactive() raises:
# Edges are excluded from evolution and always go inactive.
var grid = Grid[8, 8]()
for coord in [(0, 0), (7, 0), (0, 7), (7, 7), (4, 0), (0, 4)]:
grid[coord] = 1
grid.evolve()
for x in range(8):
assert_equal(grid[(x, 0)], 0)
assert_equal(grid[(x, 7)], 0)
for y in range(8):
assert_equal(grid[(0, y)], 0)
assert_equal(grid[(7, y)], 0)
def main() raises:
test_glider_grid()
test_to_index_lambda()
test_list_expression()
test_tuple_mixed_types()
test_print_grid_runs()
test_comptime_constants()
test_integer_division_operators()
test_comptime_conversions()
test_comptime_grid_setup()
test_grid_init()
test_grid_parameters()
test_grid_indexing()
test_grid_static_conversions()
test_grid_glider_setup()
test_is_valid_coord()
test_setitem_out_of_bounds_is_a_no_op()
test_checked_getitem()
test_random_grid_single_clump()
test_random_grid_no_clumps()
test_random_grid_default_clumps()
test_evolve_still_life()
test_evolve_blinker_oscillates()
test_evolve_underpopulation()
test_evolve_birth()
test_evolve_edges_go_inactive()
@@ -0,0 +1,391 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
# tests.mojo
# Tests for death.mdx code examples and prose claims.
#
# The page demonstrates destruction by printing from `__deinit__()`. Printing
# can't be asserted, so the types here record into a list instead and the tests
# assert the recorded order. The recorded strings match the page's output text,
# so a change in either the order or the wording fails a test.
#
# Page claims, and where each is verified:
# 1. Destruction is as-soon-as-possible: a value dies after its last use,
# not at the end of a block or expression.
# -> test_asap_within_expression, test_asap_before_block_end
# 2. The documented destruction order for `a + (b - c) * d`, including the
# three unnamed intermediates.
# -> test_documented_destruction_order (asserts all seven entries in order)
# 3. Every value is initialized once and deinitialized once.
# -> test_documented_destruction_order (seven values, seven records)
# 4. `__deinit__()` uses the `deinit` convention, and the value and its
# fields stay valid while it runs.
# -> test_fields_valid_during_deinit
# 5. Mojo generates `__deinit__()` for every struct with deinitializable
# fields.
# -> test_generated_deinitializer (conformance, no explicit method)
# 6. A deinitializer can move values out of fields without reinitializing
# them.
# -> test_move_out_of_field
# 7. Struct fields use ASAP destruction within `__deinit__()`, so a field
# whose last use is earlier dies earlier.
# -> test_field_asap_order
# 8. A custom deinitializer can close an owned resource.
# -> test_custom_deinitializer_closes_file
# 9. `_ = value` marks a last use, so the deinitializer runs after that
# statement, which extends the value's lifetime to that point.
# -> test_lifetime_extension_orders_release
# 10. An RAII guard is released too early without the extension, and neither
# case is a compiler error.
# -> test_guard_released_early, test_guard_held_to_discard
# 11. Discarding a move-only value needs no transfer sigil.
# -> test_discard_without_transfer_sigil
#
# Not tested:
# - "In general, don't call `__deinit__()` directly" (advice, not a compiler
# rule: the direct call is accepted, which is what the page's own carve-out
# for wrapping a deinitializer in parameterized code depends on, and what
# explicit-destroy.mdx's `implicit_consumer` lambda uses)
# - the use-after-free half of the origin-erasure hazard: reading through a
# pointer whose owner has already died is undefined behavior, so the test
# asserts only the extended case, where the read is well defined
from std.os import remove
from std.os.path import exists
from std.tempfile import NamedTemporaryFile
from std.testing import assert_equal, assert_false, assert_true
from std.traits import Deinitable
from std.memory import Allocation, Layout, alloc, dealloc
# --- Recording helper: an origin-erased handle to a list of events ---
comptime Recorder = Pointer[List[String], MutUntrackedOrigin]
def recorder(mut events: List[String]) -> Recorder:
return Pointer(to=events).unsafe_origin_cast[MutUntrackedOrigin]()
def record(into: Recorder, var event: String):
into[].append(event^)
# --- When Mojo destroys values ---
@fieldwise_init
struct Number(Copyable, Writable):
var value: Int
var events: Recorder
def __deinit__(deinit self):
record(self.events, String("Destroying Number(value=", self.value, ")"))
def __add__(self, other: Self) -> Self:
return Number(self.value + other.value, self.events)
def __sub__(self, other: Self) -> Self:
return Number(self.value - other.value, self.events)
def __mul__(self, other: Self) -> Self:
return Number(self.value * other.value, self.events)
def write_to(self, mut writer: Some[Writer]):
writer.write("Number(value=", self.value, ")")
def test_documented_destruction_order() raises:
var events = List[String]()
var log = recorder(events)
var a = Number(1, log)
var b = Number(2, log)
var c = Number(3, log)
var d = Number(4, log)
# 1 2 3 4
var rendered = String(a + (b - c) * d)
assert_equal(rendered, "Number(value=-3)")
# The page's documented order: the parenthesized subtraction first, then
# the multiplication, then the addition, then the result.
var expected = [
"Destroying Number(value=3)", # subtraction
"Destroying Number(value=2)", # subtraction
"Destroying Number(value=-1)", # multiplication, intermediate
"Destroying Number(value=4)", # multiplication
"Destroying Number(value=-4)", # addition, intermediate
"Destroying Number(value=1)", # addition
"Destroying Number(value=-3)", # result
]
assert_equal(len(events), len(expected))
for i in range(len(expected)):
assert_equal(events[i], expected[i])
def test_asap_within_expression() raises:
# An intermediate dies while the enclosing expression is still evaluating,
# so an event is already recorded before the statement ends.
var events = List[String]()
var log = recorder(events)
var a = Number(1, log)
var b = Number(2, log)
# The intermediate from `a + b` is destroyed before `len(events)` is read
# later in the same expression, so the count is already non-zero.
var sum_plus_count = (a + b).value + len(events)
assert_true(sum_plus_count > 3)
# Three values in total: the intermediate, then `a` and `b`.
assert_equal(len(events), 3)
def test_asap_before_block_end() raises:
# `n`'s last use is the assert below, not the end of the function.
var events = List[String]()
var log = recorder(events)
var counted: Int
var n = Number(7, log)
counted = n.value
assert_equal(len(events), 1) # already destroyed, mid-block
assert_equal(counted, 7)
# --- Deinitializer behavior ---
@fieldwise_init
struct Fields(Movable):
var name: String
var events: Recorder
def __deinit__(deinit self):
# The value and its fields are still valid here.
record(self.events, String("deinit saw ", self.name))
def test_fields_valid_during_deinit() raises:
var events = List[String]()
var log = recorder(events)
_ = Fields("intact", log)
assert_equal(len(events), 1)
assert_equal(events[0], "deinit saw intact")
@fieldwise_init
struct NoExplicitDeinit(Movable):
var owned_string: String # a deinitializable field
def test_generated_deinitializer() raises:
# No `__deinit__()` is written, yet the type is `Deinitable`.
assert_true(conforms_to(NoExplicitDeinit, Deinitable))
_ = NoExplicitDeinit("released by the generated deinitializer")
# --- Moving values out of fields ---
@fieldwise_init
struct Holder(Movable):
var name: String
var events: Recorder
def __deinit__(deinit self):
var name = self.name^ # OK: can take ownership of fields
record(self.events, String("moved out ", name))
def test_move_out_of_field() raises:
var events = List[String]()
var log = recorder(events)
_ = Holder("payload", log)
assert_equal(events[0], "moved out payload")
@fieldwise_init
struct Marker(Movable):
var name: String
var events: Recorder
def use(self):
record(self.events, String("use ", self.name))
def __deinit__(deinit self):
record(self.events, String("destroy ", self.name))
@fieldwise_init
struct S(Movable):
var a: Marker
var b: Marker
var events: Recorder
def __deinit__(deinit self):
# `a` has no use in this body, so Mojo destroys it here.
self.b.use()
# `b`'s last use was the line above, so Mojo destroys it there.
def test_field_asap_order() raises:
var events = List[String]()
var log = recorder(events)
_ = S(Marker("a", log), Marker("b", log), log)
var expected = ["destroy a", "use b", "destroy b"]
assert_equal(len(events), len(expected))
for i in range(len(expected)):
assert_equal(events[i], expected[i])
# --- Custom deinitializers ---
struct QuickLogger:
var temporary_file: NamedTemporaryFile
var path: String
def __init__(out self) raises:
self.temporary_file = NamedTemporaryFile(mode="w", delete=False)
self.path = self.temporary_file.name
def log(mut self, message: String) raises:
self.temporary_file.write(message + "\n")
def __deinit__(deinit self):
try:
self.temporary_file.close()
except:
pass
def test_custom_deinitializer_closes_file() raises:
var path: String
var ql = QuickLogger()
path = ql.path
ql.log("This is a test log message.")
ql.log("This is the last use of 'ql'")
# `ql` is destroyed above, at its last use, so the file is closed and
# (with delete=False) still on disk.
assert_true(exists(path))
remove(path)
assert_false(exists(path))
# --- Explicit lifetime extension ---
@fieldwise_init
struct Guard(Movable):
var name: String
var events: Recorder
def __deinit__(deinit self):
record(self.events, String("released ", self.name))
def test_guard_released_early() raises:
# No extension: the guard's last use is the length check, so the lock is
# released before the work it was meant to protect. This compiles, and the
# compiler reports nothing.
var events = List[String]()
var log = recorder(events)
var g = Guard("early", log)
assert_equal(g.name.byte_length(), 5) # last use of `g`
record(log, "work")
assert_equal(events[0], "released early")
assert_equal(events[1], "work")
def test_guard_held_to_discard() raises:
# With the extension, the release lands after the work.
var events = List[String]()
var log = recorder(events)
var g = Guard("held", log)
record(log, "work")
_ = g # last use of `g` moves here
assert_equal(events[0], "work")
assert_equal(events[1], "released held")
def test_lifetime_extension_orders_release() raises:
# The page's `s` and `t` pair: `s` dies at its last use, while `t` is held
# until the discard line.
var events = List[String]()
var log = recorder(events)
var s = Guard("s", log)
assert_equal(s.name, "s") # last use of `s`
var t = Guard("t", log)
assert_equal(t.name, "t")
record(log, "some time later")
_ = t # `t` is destroyed after this line
var expected = ["released s", "some time later", "released t"]
for i in range(len(expected)):
assert_equal(events[i], expected[i])
struct Owner(Movable):
var storage: Allocation[Int64]
def __init__(out self):
self.storage = alloc(Layout[Int64](count=1))
self.storage.unsafe_span().fill(7)
def __deinit__(deinit self):
dealloc(self.storage^)
def test_origin_erased_pointer_needs_extension() raises:
# `unsafe_ptr()` alone borrows the owner, so origins keep it alive. Erasing
# the origin removes that protection, and the discard is what keeps the
# storage valid for the read.
var o = Owner()
var p = o.storage.unsafe_ptr().unsafe_origin_cast[MutUntrackedOrigin]()
assert_equal(p[], 7)
_ = o # without this, the read above is a use-after-free
def test_discard_without_transfer_sigil() raises:
# A move-only value: no `^` is needed to discard it, since the compiler
# doesn't move the discarded value.
var events = List[String]()
var log = recorder(events)
var only_movable = Guard("move-only", log)
_ = only_movable
assert_equal(events[0], "released move-only")
def main() raises:
test_documented_destruction_order()
test_asap_within_expression()
test_asap_before_block_end()
test_fields_valid_during_deinit()
test_generated_deinitializer()
test_move_out_of_field()
test_field_asap_order()
test_custom_deinitializer_closes_file()
test_guard_released_early()
test_guard_held_to_discard()
test_lifetime_extension_orders_release()
test_origin_erased_pointer_needs_extension()
test_discard_without_transfer_sigil()
@@ -0,0 +1,457 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
# tests.mojo
# Tests for explicit-destroy.mdx code examples and prose claims.
#
# The page demonstrates destruction by printing. Printing can't be asserted, so
# the types here record into a list and the tests assert the recorded strings
# against the page's documented output, so a change in either the order or the
# wording fails a test.
#
# Page claims, and where each is verified:
# 1. `Deinitable where False` opts a type out of automatic destruction, and
# its values must be consumed by a named deinitializer or transferred.
# -> test_named_deinitializer_consumes, test_transfer_defers_destruction;
# the failure to consume is claim C1 below
# 2. A type can offer several cleanup paths, one per named deinitializer.
# -> test_multiple_cleanup_paths
# 3. A named deinitializer can raise; `__deinit__()` can't.
# -> test_raising_deinitializer; `__deinit__()` is claim C2
# 4. `deinit self` consumes the value at the call, whether the call returns
# or raises, so the caller can't invoke a second deinitializer.
# -> test_raising_deinitializer_consumes (the caller needs no cleanup on
# the handler path); the second call is claim C3
# 5. Explicitly destroyed fields must be disposed before a deinitializer
# raises; implicitly destructible fields are cleaned up during unwinding.
# -> test_dispose_before_raise, test_implicit_field_cleaned_on_unwind;
# raising with a live linear field is claim C4
# 6. A custom `where` message improves the diagnostic.
# -> not runtime-testable; claim C1 carries the message text
# 7. Parameterized code over `AnyType`/`Movable` accepts explicitly destroyed
# values but can't destroy them, except by returning them or by receiving
# a deinitializer.
# -> test_pass_through, test_consuming_method, test_deinitable_function;
# the abandoning form is claim C5
# 8. The documented output of the `Tally` and `Basic` examples.
# -> test_documented_tally_output, test_documented_basic_output
# 9. A lambda supplies the type-specific deinitializer a parametric consumer
# can't name.
# -> test_consuming_method
# 10. One generic lambda covers every `Deinitable` type.
# -> test_implicit_consumer_covers_deinitable; its limit is claim C7
#
# Compile errors the page describes, or that these claims imply. Each is a
# compile failure, so it can't run here. Verified against the compiler on
# 2026-08-21, Mojo 1.1.0.dev0, and recorded with the diagnostic that fires:
# C1. A value left unconsumed: "'tally' abandoned without being explicitly
# destroyed: type 'Tally' does not conform to 'Deinitable' and must be
# explicitly destroyed". With a `where` message, that message replaces
# the trailing explanation.
# C2. `raises` on `__deinit__()`: "destructor must not declare 'raises';
# remove the 'raises' keyword"
# C3. A second deinitializer after a raising one, including in the `except`
# block: "use of uninitialized value 't'"
# C4. A deinitializer that raises while an explicitly destroyed field is
# still live: "'self' abandoned without being explicitly destroyed: An
# `Allocation` owns heap storage and must be consumed before it goes out
# of scope."
# C5. `def owning_function[T: AnyType](var value: T)`: "'value' abandoned
# without being explicitly destroyed: unhandled explicitly destroyed
# type 'AnyType'", with the note "consider adding trait conformance to
# Deinitable". The error is reported at the function's own definition,
# not at a call site.
# C6. A function type with a `deinit` argument: "function types do not
# support 'deinit'; replace with 'var'"
# C7. `implicit_consumer[Tally]`, instantiating the `Deinitable` lambda for
# an explicitly destroyed type: "parameter 'T' has 'Deinitable' type,
# but value has type 'AnyStruct[Tally]'"
#
# Mechanics worth knowing, confirmed while writing these tests:
# M1. A runtime argument can't carry an inline function type. The page's
# `consuming_function`/`consuming_method` signatures are right because
# they name the type as a parameter (`Cleanup: def(var T)`); spelling it
# `consume: def(var T)` instead fails inside the body and at the call.
# M2. A parametric lambda stays parametric, so `Cleanup` binds only after
# instantiation: `implicit_consumer[Basic]`, not `implicit_consumer`.
# Binding the lambda with `var` instead of `comptime` also fails, since
# it decays to a thin function pointer, which is a value, not a type.
# M3. Calling a named deinitializer on a temporary needs no transfer sigil:
# `Transaction(log, 0).rollback()` compiles, and adding `^` warns
# "transfer from an owned value has no effect and can be removed".
#
from std.memory import Allocation, Layout, alloc, dealloc
from std.reflection import reflect
from std.testing import assert_equal, assert_raises
# Testing constraint worth knowing: any raising call, including `assert_equal`,
# made while an explicitly destroyed value is still live leaves that value
# unconsumed on the unwind path, which the compiler rejects with "value was not
# consumed when an error is thrown". These tests read what they need into a
# local, consume the value, and assert afterward.
# --- Recording helper: an origin-erased handle to a list of events ---
comptime Recorder = Pointer[List[String], MutUntrackedOrigin]
def recorder(mut events: List[String]) -> Recorder:
return Pointer(to=events).unsafe_origin_cast[MutUntrackedOrigin]()
def record(into: Recorder, var event: String):
into[].append(event^)
# --- Opting out of automatic destruction ---
struct Example(Deinitable where False):
var events: Recorder
def __init__(out self, events: Recorder):
self.events = events
def cleanup(deinit self):
record(self.events, "cleaned up")
def test_named_deinitializer_consumes() raises:
var events = List[String]()
var log = recorder(events)
var value = Example(log)
value^.cleanup()
assert_equal(len(events), 1)
assert_equal(events[0], "cleaned up")
def hand_back(var value: Example) -> Example:
return value^
def test_transfer_defers_destruction() raises:
# Transferring the value out of scope satisfies the requirement at this
# point; the destruction obligation moves with the value.
var events = List[String]()
var log = recorder(events)
var value = hand_back(Example(log))
var before_cleanup = len(events) # nothing destroyed yet
value^.cleanup()
assert_equal(before_cleanup, 0)
assert_equal(len(events), 1)
# --- When to use explicit destruction: multiple cleanup paths ---
struct Transaction(
Deinitable where (False, "call 'commit()' or 'rollback()'"), Movable
):
var events: Recorder
var rows: Int
def __init__(out self, events: Recorder, rows: Int):
self.events = events
self.rows = rows
def commit(deinit self) raises:
if self.rows == 0:
raise Error("nothing to commit")
record(self.events, String("committed ", self.rows))
def rollback(deinit self):
record(self.events, "rolled back")
struct MutexGuard(Deinitable where False, Movable):
var events: Recorder
def __init__(out self, events: Recorder):
self.events = events
record(self.events, "locked")
def unlock(deinit self):
record(self.events, "unlocked")
def test_multiple_cleanup_paths() raises:
var events = List[String]()
var log = recorder(events)
Transaction(log, 3).commit()
Transaction(log, 0).rollback()
assert_equal(events[0], "committed 3")
assert_equal(events[1], "rolled back")
def test_cleanup_order_with_a_guard() raises:
var events = List[String]()
var log = recorder(events)
var guard = MutexGuard(log)
record(log, "critical section")
guard^.unlock() # the lock releases exactly here
var expected = ["locked", "critical section", "unlocked"]
for i in range(len(expected)):
assert_equal(events[i], expected[i])
# --- Raising deinitializers ---
def test_raising_deinitializer() raises:
var events = List[String]()
var log = recorder(events)
with assert_raises(contains="nothing to commit"):
Transaction(log, 0).commit()
assert_equal(len(events), 0) # the failing path recorded nothing
def test_raising_deinitializer_consumes() raises:
# The value is consumed at the call, so the handler has no cleanup left to
# do and the compiler asks for none.
var events = List[String]()
var log = recorder(events)
var caught = String("")
var t = Transaction(log, 0)
try:
t^.commit()
except e:
caught = String(e)
assert_equal(caught, "nothing to commit")
struct Counters(
Deinitable where (False, "call 'flush()' or 'drop()'"), Movable
):
var counts: Allocation[Int64]
var events: Recorder
def __init__(out self, buckets: Int, events: Recorder):
self.counts = alloc(Layout[Int64](count=buckets))
self.counts.unsafe_span().fill(0)
self.events = events
def bump(mut self, bucket: Int):
self.counts.unsafe_span()[bucket] += 1
# The linear field is released first, so the raise happens with no field
# left to dispose of. Raising before the `dealloc` doesn't compile: see C4.
def flush(deinit self) raises:
var total = Int(self.counts.unsafe_span()[0])
dealloc(self.counts^)
record(self.events, "storage released")
if total == 0:
raise Error("nothing recorded")
record(self.events, String("flushed ", total))
def drop(deinit self):
dealloc(self.counts^)
def test_dispose_before_raise() raises:
var events = List[String]()
var log = recorder(events)
with assert_raises(contains="nothing recorded"):
Counters(2, log).flush()
# The storage was freed before the failure was reported.
assert_equal(events[0], "storage released")
assert_equal(len(events), 1)
def test_dispose_before_raise_success_path() raises:
var events = List[String]()
var log = recorder(events)
var counters = Counters(2, log)
counters.bump(0)
counters^.flush()
assert_equal(events[0], "storage released")
assert_equal(events[1], "flushed 1")
struct Draft(Deinitable where (False, "call 'save()' or 'discard()'"), Movable):
var data: String # implicitly destructible
def __init__(out self, var data: String):
self.data = data^
def save(deinit self) raises:
if self.data.byte_length() == 0:
raise Error("nothing to save") # raises with the field still live
print(self.data)
def discard(deinit self):
pass
def test_implicit_field_cleaned_on_unwind() raises:
# Unlike a linear field, an implicitly destructible field can still be live
# when the deinitializer raises. It's released during unwinding.
with assert_raises(contains="nothing to save"):
Draft("").save()
# --- Parameterized code and explicit destruction ---
def deinitable_function[T: Deinitable](var value: T):
pass # value.__deinit__() called automatically
def pass_through[T: Movable](var value: T) -> T:
# perform work with value
return value^
def consuming_method[
T: Movable, //, Cleanup: def(var T)
](var value: T, consume: Cleanup) -> String:
var name = String(reflect[T].name())
consume(value^)
return name
# --- Example types for parameterized destruction ---
@fieldwise_init
struct Basic(Movable):
var string: String
var events: Recorder
def __deinit__(deinit self):
record(self.events, String("Destroying Basic: ", self.string))
struct Tally(
Deinitable where (False, "call 'destroy()' to free the counters"), Movable
):
var counts: Allocation[Int64]
var events: Recorder
def __init__(out self, buckets: Int, events: Recorder):
self.counts = alloc(Layout[Int64](count=buckets))
self.counts.unsafe_span().fill(0)
self.events = events
def record_bucket(mut self, bucket: Int):
self.counts.unsafe_span()[bucket] += 1
def destroy(deinit self):
record(
self.events,
String("Destroying Tally: ", self.counts.unsafe_span()),
)
dealloc(self.counts^)
def test_deinitable_function() raises:
var events = List[String]()
var log = recorder(events)
deinitable_function(Basic("implicit", log))
assert_equal(events[0], "Destroying Basic: implicit")
def test_documented_tally_output() raises:
var events = List[String]()
var log = recorder(events)
var tally = Tally(3, log)
tally.record_bucket(2)
tally = pass_through(tally^)
tally^.destroy()
assert_equal(events[0], "Destroying Tally: [0, 0, 1]")
def test_documented_basic_output() raises:
var events = List[String]()
var log = recorder(events)
var basic = Basic("Hello", log)
_ = pass_through(basic^)
assert_equal(events[0], "Destroying Basic: Hello")
def test_pass_through() raises:
# The function doesn't need to know the destruction model of either type.
var events = List[String]()
var log = recorder(events)
var tally = pass_through(Tally(2, log))
tally^.destroy()
assert_equal(events[0], "Destroying Tally: [0, 0]")
def test_consuming_method() raises:
var events = List[String]()
var log = recorder(events)
var tally = Tally(2, log)
tally.record_bucket(1)
comptime tally_consumer = lambda (var t: Tally): t^.destroy()
var name = consuming_method(tally^, tally_consumer)
# `reflect` reports the module-qualified name.
assert_equal(name, "tests.Tally")
assert_equal(events[0], "Destroying Tally: [0, 1]")
def test_implicit_consumer_covers_deinitable() raises:
var events = List[String]()
var log = recorder(events)
# Works across all Deinitable types. The instantiation is required: a
# parametric lambda stays parametric, and `Cleanup` is one concrete
# function type.
comptime implicit_consumer = lambda [T: Deinitable](
var value: T
): T.__deinit__(value^)
var name = consuming_method(Basic("World", log), implicit_consumer[Basic])
assert_equal(name, "tests.Basic")
assert_equal(events[0], "Destroying Basic: World")
def main() raises:
test_named_deinitializer_consumes()
test_transfer_defers_destruction()
test_multiple_cleanup_paths()
test_cleanup_order_with_a_guard()
test_raising_deinitializer()
test_raising_deinitializer_consumes()
test_dispose_before_raise()
test_dispose_before_raise_success_path()
test_implicit_field_cleaned_on_unwind()
test_deinitable_function()
test_documented_tally_output()
test_documented_basic_output()
test_pass_through()
test_consuming_method()
test_implicit_consumer_covers_deinitable()
@@ -0,0 +1,182 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
# tests.mojo
# Tests for initialization.mdx code examples and prose claims.
#
# Page claims, and where each is verified:
# 1. Calling `Person("Alice", 30)` is syntactic sugar for calling the
# initializer directly, `Person.__init__("Alice", 30)`.
# -> test_initializer_call_is_sugar (both spellings produce the same value)
# 2. A struct needs both fieldwise and logical initialization before use.
# -> test_construct_establishes_both, test_declare_then_construct
# 3. An initializer must populate every field.
# -> not runtime-testable; see "Compile errors" below, claim C2
# 4. The initializer signature doesn't have to mirror the struct's fields:
# parameters, constants, and external values can initialize them.
# -> test_parameter_initialization, test_constant_initialization,
# test_external_value_initialization
# 5. Methods can't be called until all fields are initialized.
# -> not runtime-testable; see claim C3
# 6. Field initialization is limited to `__init__()` methods; regular methods
# can't initialize individual fields of an `out` argument.
# -> not runtime-testable; see claims C4 and C5
#
# Compile errors the page describes. Each is a compile failure, so it can't run
# here. Verified against the compiler on 2026-08-21, Mojo 1.1.0.dev0, and
# recorded with the diagnostic that fires:
# C1. Fields assigned individually, without an `__init__()` call:
# "'me' used with all fields manually initialized but without calling an
# '__init__' method"
# C2. A field left unset in `__init__()`:
# "'self.age' is uninitialized at the implicit return from this function"
# C3. A method called before every field is set:
# "use of uninitialized value 'self.name'"
# C4. `out self` on a method other than `__init__()`:
# "'self' argument must have type 'Self'; use a 'where' clause to
# constrain the 'Self' type instead"
# C5. A regular method assigning every field of an `out` argument: the same
# diagnostic as C1, reported against that argument.
#
# The page shows two structs, both named `Person`: one declares `__init__()`,
# the other uses `@fieldwise_init`. One file can't hold two types of the same
# name, so the second is `FieldwisePerson` here.
from std.math import pi
from std.testing import assert_equal, assert_true
# --- The basics ---
struct Person:
var name: String
var age: Int
def __init__(out self, name: String, age: Int):
self.name = name
self.age = age
def test_construct_establishes_both() raises:
var me = Person("Alice", 30)
assert_equal(me.name, "Alice")
assert_equal(me.age, 30)
def test_initializer_call_is_sugar() raises:
var sugared = Person("Alice", 30)
var direct: Person
direct = Person.__init__("Alice", 30) # identical to the line above
assert_equal(sugared.name, direct.name)
assert_equal(sugared.age, direct.age)
# --- Fieldwise vs logical initialization ---
@fieldwise_init
struct FieldwisePerson(Writable):
var name: String
var age: Int
def test_declare_then_construct() raises:
var me: FieldwisePerson # declared, not initialized
me = FieldwisePerson("Alice", 30) # logically and fieldwise initialized
assert_equal(me.name, "Alice")
assert_equal(me.age, 30)
# `print(me)` on the page relies on the `Writable` default that reflection
# supplies, since the struct writes no `write_to()` of its own. The default
# leads with the struct's own name, so the page's `Person` renders as
# "Person(name=Alice, age=30)". The rendering is a stdlib default, not a
# page claim.
assert_equal(String(me), "FieldwisePerson(name=Alice, age=30)")
# --- Inside __init__() ---
@fieldwise_init
struct Greeter:
var name: String
def greeting(self) -> String:
return String("hello ", self.name)
def test_methods_after_fields_are_set() raises:
# The page's `greet()` example calls a method only after every field is
# set; that ordering is what compiles.
var g = Greeter("Alice")
assert_equal(g.greeting(), "hello Alice")
# --- Initializing fields from parameters ---
struct Buffer[T: Copyable & Deinitable, Count: Int]:
var _store: List[Self.T]
def __init__(out self):
self._store = List[Self.T](capacity=Self.Count)
def append(mut self, var value: Self.T):
self._store.append(value^)
def test_parameter_initialization() raises:
var b = Buffer[Int, 8]()
assert_equal(len(b._store), 0)
b.append(1)
assert_equal(len(b._store), 1)
# --- Initializing fields from constants and external values ---
struct Config:
var string: String
var default_angle: Float64
var uuid: String
def __init__(out self):
self.string = "" # constant
self.default_angle = pi / 2.0 # external value
self.uuid = Self._uuid()
@staticmethod
def _uuid() -> String:
return String("00000000-0000-0000-0000-000000000000")
def test_constant_initialization() raises:
var c = Config()
assert_equal(c.string, "")
def test_external_value_initialization() raises:
var c = Config()
assert_equal(c.default_angle, pi / 2.0)
assert_true(c.default_angle > 1.5707 and c.default_angle < 1.5708)
assert_equal(c.uuid.byte_length(), 36)
def main() raises:
test_construct_establishes_both()
test_initializer_call_is_sugar()
test_declare_then_construct()
test_methods_after_fields_are_set()
test_parameter_initialization()
test_constant_initialization()
test_external_value_initialization()
@@ -0,0 +1,334 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
# tests.mojo
# Tests for life.mdx code examples.
#
# Not tested (no runnable behavior to assert from this file):
# - `struct Target` with an `@implicit` initializer whose body is `# ...`
# (a signature sketch; `Source` is never defined on the page)
# - the bare `def __init__(out self, *, copy: Self)` signature fragment
# - the bare `def __init__(out self, *, deinit move: Self)` signature fragment
# - "An initializer must set up every field in a value" (a compile error;
# verified separately as `'self.b' is uninitialized at the implicit return
# from this function`)
# - "All initializers use the `out self` argument convention" (a compile
# error; verified as `__init__ method must return Self type with 'out'
# argument`)
# - transferring a `Pinned` value (a compile error; the type's immovability
# is asserted here through `conforms_to` instead)
# - the claim that braced shorthand helps most for compiler-inferred
# parameterized types (prose pointer, deliberately unillustrated)
from std.atomic import Atomic
from std.memory import OwnedPointer
from std.testing import assert_equal, assert_false, assert_true
from std.traits import (
IsTriviallyCopyable,
IsTriviallyDeinitable,
IsTriviallyMovable,
)
# --- Fieldwise initialization ---
# The page shows both of these as `MyStruct`, once generated and once written
# out, so they are renamed here to coexist in one file.
@fieldwise_init
struct MyStructFieldwise:
var field1: Int
var field2: String
struct MyStructHandWritten:
var field1: Int
var field2: String
def __init__(out self, field1: Int, field2: String):
self.field1 = field1
self.field2 = field2
def test_fieldwise_and_hand_written_agree() raises:
var generated = MyStructFieldwise(1, "Hello")
var written = MyStructHandWritten(1, "Hello")
assert_equal(generated.field1, written.field1)
assert_equal(generated.field2, written.field2)
assert_equal(generated.field2, "Hello")
# --- Overloading initializers, and delegating between them ---
struct RetryPolicy:
var max_attempts: Int
var delay_ms: Int
def __init__(out self):
self = self.__init__(3)
def __init__(out self, max_attempts: Int, delay_ms: Int = 1000):
self.max_attempts = max_attempts
self.delay_ms = delay_ms
def test_initializer_overloads() raises:
var standard = RetryPolicy()
var persistent = RetryPolicy(10)
var aggressive = RetryPolicy(10, 250)
# The no-argument overload delegates, so it picks up the default delay.
assert_equal(standard.max_attempts, 3)
assert_equal(standard.delay_ms, 1000)
assert_equal(persistent.max_attempts, 10)
assert_equal(persistent.delay_ms, 1000)
assert_equal(aggressive.max_attempts, 10)
assert_equal(aggressive.delay_ms, 250)
# --- No-initializer types ---
struct HTTPStatus:
comptime OK = 200
comptime NOT_FOUND = 404
comptime INTERNAL_SERVER_ERROR = 500
@staticmethod
def is_success(code: Int) -> Bool:
# 2xx is the HTTP status success class
return 200 <= code < 300
def handle(status_code: Int) -> String:
if HTTPStatus.is_success(status_code):
return "ok"
return "failed"
def test_no_initializer_type() raises:
assert_equal(HTTPStatus.OK, 200)
assert_equal(HTTPStatus.NOT_FOUND, 404)
assert_equal(HTTPStatus.INTERNAL_SERVER_ERROR, 500)
# Both range bounds, to pin the chained comparison.
assert_false(HTTPStatus.is_success(199))
assert_true(HTTPStatus.is_success(200))
assert_true(HTTPStatus.is_success(299))
assert_false(HTTPStatus.is_success(300))
assert_equal(handle(204), "ok")
assert_equal(handle(404), "failed")
# --- Initializers and implicit conversion ---
def test_optional_implicit_conversion() raises:
var greeting: Optional[String] = None
assert_false(greeting)
greeting = String("Salve!")
assert_true(greeting)
assert_equal(greeting.value(), "Salve!")
struct Complex:
var real: Float64
var imag: Float64
def __init__(out self, real: Float64, imag: Float64):
self.real = real
self.imag = imag
@implicit
def __init__(out self, value: Float64):
self = Complex(value, 0.0)
def magnitude_squared(value: Complex) -> Float64:
return value.real * value.real + value.imag * value.imag
def test_implicit_conversion_on_argument() raises:
assert_equal(magnitude_squared(3.0), 9.0)
def test_implicit_conversion_on_return() raises:
assert_equal(make_complex().real, 4.0)
assert_equal(make_complex().imag, 0.0)
def make_complex() -> Complex:
# The page states that implicit conversion also applies when returning.
return 4.0
# --- Braced shorthand ---
def test_braced_shorthand() raises:
# Spelled out, as the page's "Instead of:" block shows.
assert_equal(magnitude_squared(Complex(real=3.0, imag=0.0)), 9.0)
assert_equal(magnitude_squared(Complex(3.0, 0.0)), 9.0)
assert_equal(magnitude_squared(Complex(value=3.0)), 9.0)
assert_equal(magnitude_squared(Complex(3.0)), 9.0)
# Braced, as the page's "You write:" block shows.
assert_equal(magnitude_squared({real = 3.0, imag = 0.0}), 9.0)
assert_equal(magnitude_squared({3.0, 0.0}), 9.0)
assert_equal(magnitude_squared({value = 3.0}), 9.0)
assert_equal(magnitude_squared({3.0}), 9.0)
struct Pair:
var a: Int
var b: Int
def __init__(out self, a: Int, b: Int = 0):
self.a = a
self.b = b
def total(p: Pair) -> Int:
return p.a + p.b
def test_braced_shorthand_without_implicit_conversion() raises:
# `Pair` has no `@implicit` initializer, which is the page's claim that
# braced shorthand works whether a type provides implicit initialization
# or not.
assert_equal(total({a = 1, b = 2}), 3)
assert_equal(total({1, 2}), 3)
assert_equal(total({1}), 1)
# --- Copy and move initializers ---
@fieldwise_init
struct ValueType(Copyable):
var n: Int
def test_copy_and_move_shorthands() raises:
var value = ValueType(7)
# `value.copy()` and `ValueType(copy=value)` are the same operation.
assert_equal(value.copy().n, 7)
assert_equal(ValueType(copy=value).n, 7)
# `value^` and `ValueType(move=value^)` are the same operation. The move
# initializer consumes its argument, so the long form needs the transfer.
var moved = value^
assert_equal(ValueType(move=moved^).n, 7)
def copy_return[T: Copyable](foo: T) -> T:
var copy = foo.copy()
return copy^
def test_copyable_constraint_in_generic_code() raises:
# All `Copyable` types are also `Movable`, so the copy can be transferred
# out on return.
assert_equal(copy_return(ValueType(9)).n, 9)
def test_copy_is_a_deep_copy_of_the_binding() raises:
var original = ValueType(1)
var duplicate = original.copy()
duplicate.n = 2
assert_equal(original.n, 1)
assert_equal(duplicate.n, 2)
# --- Transfer is the default ---
def test_transfer_needs_no_declared_conformance() raises:
# `RetryPolicy` declares no conformances and still transfers.
assert_true(conforms_to(RetryPolicy, Movable))
var policy = RetryPolicy(3, 1000)
var transferred = policy^
assert_equal(transferred.max_attempts, 3)
assert_equal(transferred.delay_ms, 1000)
# --- Move-only and immovable types ---
struct Pinned(Movable where False):
var n: Int
def __init__(out self, n: Int):
self.n = n
def test_move_only_types() raises:
assert_true(conforms_to(OwnedPointer[Int], Movable))
assert_false(conforms_to(OwnedPointer[Int], Copyable))
# `Atomic` is move-only, not immovable.
assert_true(conforms_to(Atomic[Int64], Movable))
assert_false(conforms_to(Atomic[Int64], Copyable))
var counter = Atomic[Int64](0)
_ = counter.fetch_add(5)
var relocated = counter^
assert_equal(relocated.load(), 5)
def test_immovable_type() raises:
assert_false(conforms_to(Pinned, Movable))
assert_false(conforms_to(Pinned, Copyable))
var pinned = Pinned(5)
assert_equal(pinned.n, 5)
# --- Trivial lifecycle methods ---
struct MoveOnlyTrivialBits:
var n: Int
def __init__(out self, n: Int):
self.n = n
def test_trivial_lifecycle_predicates() raises:
assert_true(IsTriviallyCopyable[Int])
assert_true(IsTriviallyMovable[Int])
assert_true(IsTriviallyDeinitable[Int])
# `String` disagrees across all three, so one type exercises each.
assert_false(IsTriviallyCopyable[String])
assert_true(IsTriviallyMovable[String])
assert_false(IsTriviallyDeinitable[String])
def test_trivial_predicates_require_conformance() raises:
# Each predicate is false for a type that doesn't conform to the matching
# trait, even when the bits themselves are trivial. This is what the page's
# "is true when `T` is `Copyable` and ..." wording covers.
assert_false(conforms_to(MoveOnlyTrivialBits, Copyable))
assert_false(IsTriviallyCopyable[MoveOnlyTrivialBits])
assert_true(IsTriviallyMovable[MoveOnlyTrivialBits])
assert_false(IsTriviallyMovable[Pinned])
def main() raises:
test_fieldwise_and_hand_written_agree()
test_initializer_overloads()
test_no_initializer_type()
test_optional_implicit_conversion()
test_implicit_conversion_on_argument()
test_implicit_conversion_on_return()
test_braced_shorthand()
test_braced_shorthand_without_implicit_conversion()
test_copy_and_move_shorthands()
test_copyable_constraint_in_generic_code()
test_copy_is_a_deep_copy_of_the_binding()
test_transfer_needs_no_declared_conformance()
test_move_only_types()
test_immovable_type()
test_trivial_lifecycle_predicates()
test_trivial_predicates_require_conformance()
@@ -0,0 +1,114 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
# tests.mojo
# Tests for trivial.mdx code examples and prose claims.
#
# Page claims, and where each is verified:
# 1. The three predicates import from `std.traits`.
# -> the import below; source: stdlib/std/traits/__init__.mojo:23-25
# 2. `IsTriviallyCopyable[T]` is true when `T` is `Copyable` and copying a
# value's bits has no side effects.
# -> test_trivially_copyable; source: stdlib/std/traits/copyable.mojo:93
# 3. `IsTriviallyMovable[T]` is true when `T` is `Movable` and moving a
# value's bits has no side effects.
# -> test_trivially_movable; source: stdlib/std/traits/movable.mojo:75
# 4. `IsTriviallyDeinitable[T]` is true when `T` is `Deinitable` and
# deinitialization is a no-op.
# -> test_trivially_deinitable; source: stdlib/std/traits/deinitable.mojo:97
# 5. Each predicate is a `comptime` value, so it is usable in `comptime if`
# and `comptime assert`.
# -> test_predicates_are_comptime
#
# Not tested:
# - "the compiler can optimize or eliminate them" (a codegen claim, with no
# source-level observation available from a test)
from std.testing import assert_false, assert_true
from std.traits import (
IsTriviallyCopyable,
IsTriviallyDeinitable,
IsTriviallyMovable,
)
# --- Types that stand on each side of the three predicates ---
# Bitwise copy, bitwise move, no-op deinit.
comptime Trivial = Int
@fieldwise_init
struct SideEffects(Copyable, Movable):
"""Custom lifecycle methods, so no operation is trivial."""
var value: Int
def __init__(out self, *, copy: Self):
self.value = copy.value + 1 # a side effect of copying
def __init__(out self, *, deinit move: Self):
self.value = move.value
def __deinit__(deinit self):
_ = self.value # a deinitializer body, so deinit is not a no-op
# --- IsTriviallyCopyable ---
def test_trivially_copyable() raises:
assert_true(IsTriviallyCopyable[Trivial])
assert_true(IsTriviallyCopyable[SIMD[DType.float32, 4]])
# `String` is `Copyable`, but copying owns heap storage.
assert_false(IsTriviallyCopyable[String])
assert_false(IsTriviallyCopyable[SideEffects])
# --- IsTriviallyMovable ---
def test_trivially_movable() raises:
assert_true(IsTriviallyMovable[Trivial])
assert_true(IsTriviallyMovable[SIMD[DType.float32, 4]])
assert_false(IsTriviallyMovable[SideEffects])
# --- IsTriviallyDeinitable ---
def test_trivially_deinitable() raises:
assert_true(IsTriviallyDeinitable[Trivial])
assert_true(IsTriviallyDeinitable[SIMD[DType.float32, 4]])
# `String` releases heap storage, so its deinitializer is not a no-op.
assert_false(IsTriviallyDeinitable[String])
assert_false(IsTriviallyDeinitable[SideEffects])
# --- The predicates are compile-time values ---
def test_predicates_are_comptime() raises:
comptime assert IsTriviallyCopyable[Trivial]
comptime assert not IsTriviallyDeinitable[String]
var branch_taken: Bool
comptime if IsTriviallyMovable[Trivial]:
branch_taken = True
else:
branch_taken = False
assert_true(branch_taken)
def main() raises:
test_trivially_copyable()
test_trivially_movable()
test_trivially_deinitable()
test_predicates_are_comptime()
@@ -0,0 +1,36 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
from std.testing import assert_equal
def elementwise_max(lhs: SIMD, rhs: type_of(lhs), out result: type_of(lhs)):
result = {}
comptime for i in range(lhs.length):
result[i] = lhs[i] if lhs[i] >= rhs[i] else rhs[i]
def main() raises:
comptime simd_type = SIMD[.int64, 4]
var v1 = simd_type(12, 0, 99, 77)
var v2 = simd_type(0, 92, 11, 4)
assert_equal(elementwise_max(v1, v2), simd_type(12, 92, 99, 77))
var a: Array[Float64, 5] = [2, 4, 5, 7, 8]
var b = Array[Float64, 4](fill=0)
comptime for i in range(1, 5):
b[i - 1] = a[i] + a[i - 1]
var expected: Array[Float64, 4] = [6.0, 9.0, 12.0, 15.0]
for i in range(expected.length):
assert_equal(b[i], expected[i])
@@ -0,0 +1,28 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
from std.sys import has_accelerator
def run_on_gpu():
pass
def run_on_cpu():
pass
def main():
comptime if has_accelerator():
run_on_gpu()
else:
run_on_cpu()
@@ -0,0 +1,27 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
comptime VALUE = 10
def scope_me():
print(VALUE) # prints 10
comptime VALUE = 20
# comptime VALUE = 30 # error: invalid redeclaration of VALUE
comptime if True:
comptime VALUE = 40
print(VALUE) # prints 40
print(VALUE) # prints 20
def main():
scope_me()
@@ -0,0 +1,29 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
# simple examples from the intro section
comptime NUM_TILES = 1024 // 32
comptime SIZE = 3
def get_array_size() -> Int:
return 32
def main():
comptime for i in range(4):
print(i)
var array = Array[Int, get_array_size()](fill=0)
_ = array
@@ -0,0 +1,34 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
from std.testing import assert_equal
from layout import Layout
def lookup_fn[idx: Int](value: Int) -> Int:
comptime my_constants: List[Int] = [3, 6, 9]
return comptime (my_constants[idx]) * value
def layout_size() -> Int:
comptime layout = Layout.row_major(16, 8)
var size = comptime (layout.size())
return size
def main() raises:
var x = lookup_fn[1](4)
assert_equal(x, 24)
var y = layout_size()
assert_equal(y, 128)
@@ -0,0 +1,40 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
from std.builtin.globals import global_constant
from std.testing import assert_equal
def use_lookup(idx: Int) -> Int64:
comptime numbers: Array[Int64, 10] = [
1,
3,
14,
34,
63,
101,
148,
204,
269,
343,
]
ref lookup_table = global_constant[numbers]()
if idx < len(lookup_table):
return lookup_table[idx]
else:
return 0
def main() raises:
var x = use_lookup(3)
assert_equal(x, 34)
@@ -0,0 +1,62 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
def dynamic_function(i: Int) -> Int:
return i % 4
def process(i: Int):
pass
def lookup_fn(count: Int):
comptime list_of_values: List[Int] = [1, 3, 5, 7]
for i in range(count):
# Some computation, doesn't matter what it is.
var idx = dynamic_function(i)
# This is the problem
var tmp: List[Int] = materialize[list_of_values]()
var lookup = tmp[idx]
# tmp is destroyed here
# Use the value
process(lookup)
def lookup_fn2(count: Int):
comptime list_of_values: List[Int] = [1, 3, 5, 7]
var list = materialize[list_of_values]()
for i in range(count):
# Some computation, doesn't matter what it is.
var idx = dynamic_function(i)
var lookup = list[idx]
# Use the value
process(lookup)
def main():
lookup_fn(4)
lookup_fn2(4)
comptime str_literal = "Hello" # at compile time, a StringLiteral
var str = str_literal # at run time, a String.
var static_str: StaticString = str_literal # or a StaticString
# end of examples
_, _ = str, static_str
@@ -0,0 +1,636 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
# tests.mojo
# Tests for reflection.mdx code examples.
# Skip: show_type/show_layout/log print output (path-dependent),
# origin_of abort path (aborts by design),
# get_linkage_name exact value (mangled symbol),
# "no runtime cost" and "resolves at compile time" (codegen claims),
# "name-based lookup requires a concrete type" (needs a
# compile-failure test, not a runtime one),
# the claim that a non-`@always_inline` caller reports its own line
# (does not reproduce: a plain `def` also reports the call site, so
# the behavior is optimizer-dependent and not safe to pin),
# "print cleanly, without extra code" (compiling `Sensor` with a
# `Writable` conformance and no `write_to` is the proof; the derived
# rendering itself belongs to the compiler),
# the wording of `prefix()` output (stdlib owns that format string).
#
# `reflect`, `conforms_to`, `materialize`, `type_of`, and `origin_of` are
# deliberately used without imports: the page claims they are built in, so
# adding imports here would silently retire that check.
from std.collections import Set
from std.testing import assert_equal, assert_true
from std.reflection import (
source_location,
call_location,
get_function_name,
get_linkage_name,
)
from std.os import abort
# --- Why reflection? ---
@fieldwise_init
struct Sensor(Equatable, Hashable, Writable):
var id: Int
var label: String
var reading: Float64
def test_sensor_equality() raises:
"""Equatable auto-implemented via fieldwise reflection."""
var a = Sensor(1, "temp", 98.6)
var b = Sensor(1, "temp", 98.6)
var c = Sensor(2, "pressure", 14.7)
assert_true(a == b)
assert_true(a != c)
def test_sensor_as_dict_key() raises:
"""`Hashable` plus `Equatable` lets `Sensor` key a `Dict`."""
var d = Dict[Sensor, Int]()
d[Sensor(1, "temp", 98.6)] = 10
assert_equal(d[Sensor(1, "temp", 98.6)], 10)
def test_sensor_as_set_element() raises:
"""Equal sensors collapse to a single `Set` element."""
var s = Set[Sensor]()
s.add(Sensor(1, "temp", 98.6))
s.add(Sensor(1, "temp", 98.6))
s.add(Sensor(2, "pressure", 14.7))
assert_equal(len(s), 2)
# --- Inspect a type ---
def test_base_name() raises:
"""Check `base_name()` strips parameters and module path."""
assert_equal(reflect[List[Int]].base_name(), "List")
assert_equal(reflect[Dict[String, Int]].base_name(), "Dict")
def test_name_is_qualified_where_base_name_is_not() raises:
"""`name()` adds the module path that `base_name()` strips."""
comptime full = reflect[Optional[Float64]].name()
comptime base = reflect[Optional[Float64]].base_name()
assert_true(full != base)
assert_true(full.find(base) >= 0)
assert_true(full.find(".") >= 0)
def test_name_applies_parameters() raises:
"""Distinct parameters yield distinct names; `base_name()` drops them."""
comptime int_name = reflect[Optional[Int]].name()
comptime float_name = reflect[Optional[Float64]].name()
assert_true(int_name != float_name)
assert_equal(
reflect[Optional[Int]].base_name(),
reflect[Optional[Float64]].base_name(),
)
@fieldwise_init
struct Config(Equatable):
var host: String
var port: Int
var verbose: Bool
var timeout: Float64
def test_type_name() raises:
"""Check `name()` returns the compiler-resolved name."""
comptime name = reflect[Config].name()
assert_true(name.find("Config") >= 0)
def test_field_count() raises:
"""Check `field_count()` counts the declared fields."""
assert_equal(reflect[Config].field_count(), 4)
def test_field_names() raises:
"""Check `field_names()` returns names in declaration order."""
var names = materialize[reflect[Config].field_names()]()
assert_equal(String(names[0]), "host")
assert_equal(String(names[3]), "timeout")
def test_field_types() raises:
"""Check each `field_types()` entry is usable as the field's own type."""
comptime types = reflect[Config].field_types()
comptime PortType = types[1]
var port: PortType = 8080
assert_equal(port, 8080)
def test_field_by_name() raises:
"""Check `field["host"]` gives a handle whose .T is usable."""
# `field[name]` returns a `Reflected` handle itself (here `Reflected[String]`),
# not the bare field type, so you can keep chaining reflection methods on it.
comptime host_handle = reflect[Config].field["host"]
var default_host: host_handle.T = "localhost"
assert_equal(default_host, "localhost")
comptime DefaultItemCount = 10
# `Movable & Deinitable` is the minimal bound `List[Self.T]` accepts: bare
# `Movable` leaves the field non-`Deinitable`, bare `Deinitable` leaves it
# non-`Movable`.
struct ParameterizedStruct[
T: Movable & Deinitable, item_count: Int = DefaultItemCount
]:
var list: List[Self.T]
def __init__(out self):
self.list = List[Self.T](capacity=Self.item_count)
def test_reflect_parameterized_struct() raises:
"""Index-based iteration works on a type that takes parameters."""
comptime P = ParameterizedStruct[String, item_count=5]
assert_equal(reflect[P].field_count(), 1)
var names = materialize[reflect[P].field_names()]()
assert_equal(String(names[0]), "list")
def test_parameterized_name_applies_parameters() raises:
"""Changing a parameter value changes the resolved name."""
comptime five = reflect[ParameterizedStruct[String, item_count=5]].name()
comptime ten = reflect[ParameterizedStruct[String, item_count=10]].name()
assert_true(five != ten)
# --- Detect field-level changes ---
def diff_fields[T: AnyType](a: T, b: T) -> List[String]:
comptime names = reflect[T].field_names()
comptime types = reflect[T].field_types()
var diffs = List[String]()
comptime for idx in range(reflect[T].field_count()):
comptime if conforms_to(types[idx], Equatable):
ref a_val = reflect[T].field_ref[idx](a)
ref b_val = reflect[T].field_ref[idx](b)
if a_val != b_val:
diffs.append(String(comptime (names[idx])))
return diffs^
def test_diff_fields_detects_changes() raises:
var old = Config("localhost", 8080, False, 30.0)
var new_cfg = Config("localhost", 9090, True, 30.0)
var changes = diff_fields(old, new_cfg)
assert_equal(len(changes), 2)
assert_equal(changes[0], "port")
assert_equal(changes[1], "verbose")
def test_diff_fields_identical() raises:
var a = Config("localhost", 8080, False, 30.0)
var b = Config("localhost", 8080, False, 30.0)
assert_equal(len(diff_fields(a, b)), 0)
def test_diff_fields_all_different() raises:
var a = Config("localhost", 8080, False, 30.0)
var b = Config("remote", 9090, True, 60.0)
assert_equal(len(diff_fields(a, b)), 4)
def test_diff_fields_single_field() raises:
var a = Config("localhost", 8080, False, 30.0)
var b = Config("localhost", 8080, False, 99.0)
var changes = diff_fields(a, b)
assert_equal(len(changes), 1)
assert_equal(changes[0], "timeout")
# `Opaque` conforms to neither `Equatable` nor `Copyable`, so it exercises
# the `conforms_to` guards that every all-conforming struct leaves dormant.
@fieldwise_init
struct Opaque(Movable):
var tag: Int
@fieldwise_init
struct Mixed(Movable):
var n: Int
var blob: Opaque
def test_diff_fields_skips_non_equatable() raises:
"""Non-`Equatable` fields drop out of the comparison entirely."""
var a = Mixed(1, Opaque(100))
var b = Mixed(2, Opaque(999))
var changes = diff_fields(a, b)
assert_equal(len(changes), 1)
assert_equal(changes[0], "n")
# --- Write once reuse everywhere ---
trait MakeCopyable:
def copy_to(self, mut other: Self):
comptime field_count = reflect[Self].field_count()
comptime field_types = reflect[Self].field_types()
comptime Usable = Copyable & Deinitable
comptime for idx in range(field_count):
comptime field_type = field_types[idx]
comptime if conforms_to(field_type, Usable):
reflect[Self].field_ref[idx](other) = (
reflect[Self].field_ref[idx](self).copy()
)
@fieldwise_init
struct MultiType(MakeCopyable, Writable):
var w: String
var x: Int
var y: Bool
var z: Float64
def write_to[W: Writer](self, mut writer: W):
writer.write(String(t"[{self.w}, {self.x}, {self.y}, {self.z}]"))
def test_copy_to_transfers_values() raises:
"""Check `copy_to` duplicates all Copyable fields."""
var original = MultiType("Hello", 1, True, 2.5)
var target = MultiType("", 0, False, 0.0)
original.copy_to(target)
assert_equal(target.w, "Hello")
assert_equal(target.x, 1)
assert_equal(target.y, True)
assert_equal(target.z, 2.5)
def test_copy_to_independent() raises:
"""Modifying original after copy_to doesn't affect target."""
var original = MultiType("Hello", 1, True, 2.5)
var target = MultiType("", 0, False, 0.0)
original.copy_to(target)
original.x = 999
assert_equal(target.x, 1)
def test_multitype_write_to() raises:
"""`write_to` reaches every field, so the rendering is not empty."""
var rendered = String(MultiType("Hello", 1, True, 2.5))
assert_true(rendered.startswith("["))
assert_true(rendered.endswith("]"))
assert_true(rendered.find("Hello") >= 0)
@fieldwise_init
struct Pair(MakeCopyable):
var a: Int
var b: String
def test_copy_to_on_a_second_struct() raises:
"""A differently shaped struct gets `copy_to` with no implementation."""
var src = Pair(7, "seven")
var dst = Pair(0, "")
src.copy_to(dst)
assert_equal(dst.a, 7)
assert_equal(dst.b, "seven")
@fieldwise_init
struct PartlyCopyable(MakeCopyable):
var n: Int
var blob: Opaque
def test_copy_to_skips_non_copyable_field() raises:
"""Fields outside `Copyable & Deinitable` are left untouched."""
var src = PartlyCopyable(5, Opaque(100))
var dst = PartlyCopyable(0, Opaque(999))
src.copy_to(dst)
assert_equal(dst.n, 5)
assert_equal(dst.blob.tag, 999)
# --- Field layout ---
struct Packet:
var flags: UInt8
var id: UInt32
var payload: UInt64
def test_field_offset_zero() raises:
"""First field is always at offset 0."""
assert_equal(reflect[Packet].field_offset[index=0](), 0)
def test_field_offsets_exact() raises:
"""Offsets are 0, 4, 8: three bytes of padding follow the UInt8."""
assert_equal(reflect[Packet].field_offset[index=0](), 0)
assert_equal(reflect[Packet].field_offset[index=1](), 4)
assert_equal(reflect[Packet].field_offset[index=2](), 8)
def test_field_offset_alignment() raises:
"""UInt32 field is at offset >= 4 due to alignment padding after UInt8."""
comptime off = reflect[Packet].field_offset[index=1]()
assert_true(off >= 4)
def test_field_offset_by_name() raises:
"""Check `field_offset` accepts `name=` and agrees with `index=`."""
comptime by_name = reflect[Packet].field_offset[name="id"]()
comptime by_index = reflect[Packet].field_offset[index=1]()
assert_equal(by_name, by_index)
# --- type_of ---
def make_default[T: Defaultable]() -> T:
return T()
def test_type_of() raises:
"""Check `type_of` captures the compile-time type of an expression."""
var x = 42
var y = make_default[type_of(x)]()
assert_equal(y, 0)
_ = x
# --- origin_of ---
def first_ref[T: Movable](ref list: List[T]) -> ref[list[0]] T:
if not list:
abort("empty list")
return list[0]
def test_origin_of_first_ref() raises:
"""Check `first_ref` returns a reference tied to the list's origin."""
var l: List = [1, 2, 3]
ref x = first_ref(l)
assert_equal(x, 1)
x += 10
assert_equal(l[0], 11)
assert_equal(l[1], 2)
assert_equal(l[2], 3)
# --- Source locations ---
def test_source_location_line() raises:
"""Check `source_location` returns a positive line number."""
var loc = source_location()
assert_true(loc.line() > 0)
def test_source_location_column() raises:
"""Check `source_location` returns a positive column number."""
var loc = source_location()
assert_true(loc.column() > 0)
def test_source_location_file_name() raises:
"""Check `source_location` returns a non-empty file name."""
var loc = source_location()
assert_true(loc.file_name())
def test_source_location_prefix() raises:
"""Check `prefix()` carries the message and prepends location context."""
var loc = source_location()
var msg = loc.prefix("test message")
# A position past 0 means location context precedes the message.
assert_true(msg.find("test message") > 0)
def helper_source_line() -> Int:
return source_location().line()
def test_source_location_ignores_call_site() raises:
"""`source_location` reports its own line, so two call sites agree."""
var first = helper_source_line()
var second = helper_source_line()
assert_equal(first, second)
@always_inline
def get_caller_line() -> Int:
return call_location().line()
def test_call_location() raises:
"""Check `call_location` captures the immediate caller's line, not its own.
"""
var line = get_caller_line()
assert_true(line > 0)
def test_call_location_reports_caller_line() raises:
"""The reported line is the call site, not the line inside the helper."""
var here = source_location().line()
var caller = get_caller_line()
assert_equal(caller, here + 1)
def test_call_location_tracks_each_call_site() raises:
"""Two call sites one line apart report lines one apart."""
var first = get_caller_line()
var second = get_caller_line()
assert_equal(second, first + 1)
@always_inline
def one_level_caller_line() -> Int:
return call_location().line()
@always_inline
def wrap_one_level() -> Int:
return one_level_caller_line()
@always_inline
def two_level_caller_line() -> Int:
return call_location[inline_count=2]().line()
@always_inline
def wrap_two_levels() -> Int:
return two_level_caller_line()
def test_inline_count_default_stops_at_immediate_caller() raises:
"""The default (1) reports the line inside the wrapper, so distinct call
sites agree."""
var first = wrap_one_level()
var second = wrap_one_level()
assert_equal(first, second)
def test_inline_count_two_skips_a_level() raises:
"""`inline_count=2` skips the wrapper and reports this call site."""
var here = source_location().line()
var line = wrap_two_levels()
assert_equal(line, here + 1)
@always_inline
def require(cond: Bool, msg: String = "requirement failed") raises:
if not cond:
raise Error(call_location().prefix(msg))
def test_require_carries_the_caller_message() raises:
"""`require` raises with the caller's message.
That the location is the caller's, not `require`'s, is checked directly
in `test_call_location_reports_caller_line` rather than by matching the
formatted error text.
"""
var caught = String("")
try:
require(False, "x must be > 10")
except e:
caught = String(e)
assert_true(caught.find("x must be > 10") >= 0)
# --- Function names ---
def process_data():
pass
def test_get_function_name() raises:
"""Check `get_function_name` returns the source-level name."""
comptime name = get_function_name[process_data]()
assert_equal(name, "process_data")
def test_get_linkage_name() raises:
"""Check `get_linkage_name` returns a non-empty mangled symbol."""
comptime linkage = get_linkage_name[process_data]()
assert_true(linkage)
def test_linkage_name_is_mangled() raises:
"""The linkage name is mangled, so it differs from the source name."""
comptime source = get_function_name[process_data]()
comptime linkage = get_linkage_name[process_data]()
assert_true(source != linkage)
# --- Additional methods: conforms_to and where clause ---
def eq[T: AnyType](a: T, b: T) -> Bool where conforms_to(T, Equatable):
return a == b
def test_eq_where_clause() raises:
"""Check `where conforms_to(T, Equatable)` enables `==` operator."""
assert_true(eq(1, 1))
assert_true(not eq(1, 2))
assert_true(eq("hello", "hello"))
def test_conforms_to() raises:
"""Check `conforms_to` checks compile-time trait conformance."""
assert_true(conforms_to(Int, Equatable))
assert_true(conforms_to(String, Equatable))
def main() raises:
# Why reflection?
test_sensor_equality()
test_sensor_as_dict_key()
test_sensor_as_set_element()
# Inspect a type
test_base_name()
test_name_is_qualified_where_base_name_is_not()
test_name_applies_parameters()
test_type_name()
test_field_count()
test_field_names()
test_field_types()
test_field_by_name()
test_reflect_parameterized_struct()
test_parameterized_name_applies_parameters()
# Detect field-level changes
test_diff_fields_detects_changes()
test_diff_fields_identical()
test_diff_fields_all_different()
test_diff_fields_single_field()
test_diff_fields_skips_non_equatable()
# Write once reuse everywhere
test_copy_to_transfers_values()
test_copy_to_independent()
test_multitype_write_to()
test_copy_to_on_a_second_struct()
test_copy_to_skips_non_copyable_field()
# Field layout
test_field_offset_zero()
test_field_offsets_exact()
test_field_offset_alignment()
test_field_offset_by_name()
# type_of
test_type_of()
# origin_of
test_origin_of_first_ref()
# Source locations
test_source_location_line()
test_source_location_column()
test_source_location_file_name()
test_source_location_prefix()
test_source_location_ignores_call_site()
test_call_location()
test_call_location_reports_caller_line()
test_call_location_tracks_each_call_site()
test_inline_count_default_stops_at_immediate_caller()
test_inline_count_two_skips_a_level()
test_require_carries_the_caller_message()
# Function names
test_get_function_name()
test_get_linkage_name()
test_linkage_name_is_mangled()
# Additional methods
test_eq_where_clause()
test_conforms_to()
@@ -0,0 +1,229 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
# test_operators.mojo
# Tests for operators.mdx code examples.
# Skip: hypothetical chain, String() constructor (undefined vars),
# walrus (requires input()), precedence (undefined vars),
# matrix multiplication (no built-in matrix type).
from std.testing import assert_equal
def test_arithmetic() raises:
assert_equal(7 + 3, 10) # add
assert_equal(7 - 3, 4) # subtract
assert_equal(7 * 3, 21) # multiply
def test_exponentiation_basic() raises:
assert_equal(2**8, 256) # 256 (exponentiation)
def test_unary_symbols() raises:
assert_equal(-7, -7) # -7
assert_equal(+7, 7) # 7
var a: Int8 = -128
assert_equal(~a, 127) # 127
def test_division_and_remainder() raises:
var a = -7
var b = 4
assert_equal(a / b, -1) # -1 (truncates toward zero)
assert_equal(a // b, -2) # -2 (rounds toward negative infinity)
def test_modulo() raises:
assert_equal(7 % 3, 1) # 1
assert_equal(-7 % 4, 1) # 1
assert_equal(7 % -4, -1) # -1
def test_exponentiation_right_assoc() raises:
assert_equal(2**3**2, 512) # 512, same as 2 ** (3 ** 2)
def test_comparisons() raises:
assert_equal(10 > 5, True) # True
assert_equal(10 == 10, True) # True
assert_equal(10 != 10, False) # False
def test_float_comparison() raises:
from std.math import isclose
var total: Float64 = 0.0
for _ in range(10):
total += 0.1
assert_equal(total == 1.0, False) # False
assert_equal(isclose(total, 1.0), True) # True
def test_chained_comparisons() raises:
var x = 5
assert_equal(1 < x < 10, True) # True
assert_equal(1 < x < 3, False) # False
assert_equal(1 < x <= 5 < 9, True) # True
def test_chained_len() raises:
var short_item_list: List[Int] = [1, 2, 3, 4, 5]
var ok = 0 < len(short_item_list) <= 10
assert_equal(ok, True) # True
def test_bitwise() raises:
var flags: UInt8 = 0b0000_0101
var mask: UInt8 = 0b0000_0011
assert_equal(flags & mask, 1) # 1 (only bit 0 set in both)
assert_equal(flags | mask, 7) # 7 (bits 0, 1, and 2)
assert_equal(flags ^ mask, 6) # 6 (bits 1 and 2 differ)
def test_shifts() raises:
assert_equal(1 << 4, 16) # 16
assert_equal(16 >> 2, 4) # 4
assert_equal(-16 >> 2, -4) # -4
def test_boolean_logic() raises:
# constant value on left side of 'True and ...'
# unreachable code on right side of 'True or ...'
# assert_equal(True and False, False) # False. Not testable
# assert_equal(True or False, True) # True. Not testable
assert_equal(not True, False) # False
def test_short_circuit() raises:
def always_true() -> Bool:
print("called")
return True
# "called" never prints because the left side
# of `and` is already False:
# assert_equal(always_true(), True) # True. Not testable
# assert_equal(False and always_true(), False) # False. Not testable
def test_truthiness() raises:
# var name = "Mojo"
# assert_equal(bool(name), True) # True. Not testable
pass # Not testable.
def test_membership() raises:
var colors: List[String] = ["red", "green", "blue"]
assert_equal("red" in colors, True) # True
assert_equal("yellow" not in colors, True) # True
def test_substring() raises:
var food = "peanut butter"
assert_equal("nut" in food, True) # True
def test_identity() raises:
var opt: Optional[Int] = None
assert_equal(opt is None, True) # True
opt = 42
assert_equal(opt is not None, True) # True
def test_string_concat_repeat() raises:
var greeting = "Hello" + " " + "Mojo"
assert_equal(greeting, "Hello Mojo") # Hello Mojo
assert_equal("ha" * 3, "hahaha") # hahaha
assert_equal("=" * 5, "=====") # a line of 5 equals signs
def test_string_comparison() raises:
assert_equal("apple" < "banana", True) # True
assert_equal("apple" == "apple", True) # True
assert_equal("apple" != "banana", True) # True
assert_equal("Zebra" < "ant", True) # True
assert_equal("bird" == "bird", True) # True
def test_conditional_expression() raises:
var score = 80
var result = "pass" if score > 65 else "fail"
assert_equal(result, "pass") # pass
def test_conditional_in_function_arg() raises:
def greet(name: String):
print("Hello,", name)
# assert_equal("Sami" if True else "Cass", "Sami")
# Not testable due to constant condition
# Fails CI: dead branch due to constant condition
# greet("Sami" if True else "Cass") # Hello, Sami
def test_chained_ternary() raises:
var value = 50
var label = "low" if value < 10 else "high" if value > 100 else "mid"
assert_equal(label, "mid") # mid
value = 0
assert_equal(
"low" if value < 10 else "high" if value > 100 else "mid", "low"
) # low
value = 150
assert_equal(
"low" if value < 10 else "high" if value > 100 else "mid", "high"
) # high
def test_inplace_assignment() raises:
var count = 0
count += 1
count += 1
assert_equal(count, 2) # 2
var flags: UInt8 = 0b0000_0001
flags |= 0b0000_0100
assert_equal(flags, 5) # 5 (bits 0 and 2 set)
flags &= 0b0000_0110
assert_equal(flags, 4) # 4 (only bit 2 remains set)
flags ^= 0b0000_0010
assert_equal(flags, 6) # 6 (bits 1 and 2 differ)
def main() raises:
test_arithmetic()
test_exponentiation_basic()
test_unary_symbols()
test_division_and_remainder()
test_modulo()
test_exponentiation_right_assoc()
test_comparisons()
test_float_comparison()
test_chained_comparisons()
test_chained_len()
test_bitwise()
test_shifts()
test_boolean_logic()
test_short_circuit()
test_truthiness()
test_membership()
test_substring()
test_identity()
test_string_concat_repeat()
test_string_comparison()
test_conditional_expression()
test_conditional_in_function_arg()
test_chained_ternary()
test_inplace_assignment()
@@ -0,0 +1,39 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
@fieldwise_init
struct Sentiment(Equatable, ImplicitlyCopyable):
var _value: Int
comptime NEGATIVE = Sentiment(0)
comptime NEUTRAL = Sentiment(1)
comptime POSITIVE = Sentiment(2)
def __eq__(self, other: Self) -> Bool:
return self._value == other._value
def __ne__(self, other: Self) -> Bool:
return not (self == other)
def is_happy(s: Sentiment):
if s == Sentiment.POSITIVE:
print("Yes. 😀")
else:
print("No. ☹️")
def main():
var mood = Sentiment.POSITIVE
is_happy(mood)
@@ -0,0 +1,56 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
# Docs example *only* includes the signature, to show the elements of a
# parameter list.
def my_sort[
# infer-only parameters
dtype: DType,
width: SIMDLength,
//,
# positional-only parameter
values: SIMD[dtype, width],
/,
# positional-or-keyword parameter
compare: def(Scalar[dtype], Scalar[dtype]) thin -> Int,
*,
# keyword-only parameter
reverse: Bool = False,
]() -> SIMD[dtype, width]:
var sorted = SIMD[dtype, width](values)
for output_position in range(width):
var lowest = output_position
for compare_position in range(output_position + 1, width):
if compare(sorted[lowest], sorted[compare_position]) == 1:
lowest = compare_position
if lowest != output_position:
sorted[output_position], sorted[lowest] = (
sorted[lowest],
sorted[output_position],
)
return sorted
def main():
comptime dtype = DType.int32
comptime input2 = SIMD[dtype, 8](9, 3, 3, 1, 11, 10, 5, 2)
def compare(lhs: Scalar[dtype], rhs: Scalar[dtype]) -> Int:
if lhs == rhs:
return 0
else:
return -1 if lhs < rhs else 1
comptime sorted = my_sort[input2, compare, reverse=False]()
print(sorted)
@@ -0,0 +1,85 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
# start-take-simd
def take_simd(vec: SIMD[...]):
print(vec.dtype)
print(Int(vec.length))
# end-take-simd
def take_simd2[t: DType, s: SIMDLength, //](vec: SIMD[t, s]):
print(t)
print(Int(s))
# start-interleave
def interleave(v1: SIMD, v2: type_of(v1)) -> SIMD[v1.dtype, v1.length * 2]:
var result = SIMD[v1.dtype, v1.length * 2]()
comptime for i in range(v1.length):
result[i * 2] = v1[i]
result[i * 2 + 1] = v2[i]
return result
# end-interleave
def foo[value: SIMD]():
pass
def simd_param[value: SIMD[...]]():
pass
def simd_param2[dtype: DType, size: SIMDLength, //, value: SIMD[dtype, size]]():
pass
struct SomeStruct[s: SIMD[...]]:
pass
struct SomeStruct2[dtype: DType, size: SIMDLength, //, s: SIMD[dtype, size]]:
pass
# start-automatic-parameterization-comptime
comptime SomeComptime[s: SIMD[...]] = SomeStruct[s]
# Equivalent to:
comptime SomeComptime2[
dtype: DType, size: SIMDLength, //, S: SIMD[dtype, size]
] = SomeStruct[S]
# end-automatic-parameterization-comptime
def main():
# start-take-simd-usage
var v = SIMD[.float64, 4](1.0, 2.0, 3.0, 4.0)
take_simd(v)
# end-take-simd-usage
take_simd2(v)
# start-interleave-usage
var a = SIMD[.int16, 4](1, 2, 3, 4)
var b = SIMD[.int16, 4](0, 0, 0, 0)
var c = interleave(a, b)
print(c)
# end-interleave-usage
@@ -0,0 +1,38 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
@fieldwise_init
struct Fudge[sugar: Int, cream: Int, chocolate: Int = 7](Writable):
pass
def eat(f: Fudge[5, ...]):
print("Ate", f)
def devour(f: Fudge[_, 6, _]):
print("Devoured", String(f))
def devour2(f: Fudge[_, chocolate=_, cream=6]):
print("Devoured", String(f))
def main():
eat(Fudge[5, 5, 7]())
eat(Fudge[5, 8, 9]())
# eat(Fudge[12, 5, 7]()) # invalid call to 'eat': failed to infer implicit
# parameter 'cream' of argument 'f' type 'Fudge
devour(Fudge[3, 6, 9]())
devour(Fudge[4, 6, 8]())
@@ -0,0 +1,30 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
@fieldwise_init
struct Container[ElementType: Movable & Deinitable]:
var element: Self.ElementType
@__allow_legacy_custom_self_type
def __str__[
StrElementType: Writable & Copyable & Deinitable, //
](self: Container[StrElementType]) -> String:
return String(self.element)
def main():
var float_container = Container(5.0)
var string_container = Container("Hello")
print(float_container.__str__())
print(string_container.__str__())
@@ -0,0 +1,94 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
# start-has-default
@fieldwise_init
struct HasDefault[x: Int, y: Int = 0]:
pass
comptime UseDefault = HasDefault[10]
# end-has-default
@fieldwise_init
struct MyType[s: String, i: Int, i2: Int, b: Bool = True]:
pass
# Fully-bound
def my_fn1(mt: MyType["Hello", 3, 4, True]):
pass
# Partially-bound
def my_fn2(mt: MyType["Hola", _, _, True]):
pass
# Unbound
def my_fn3(mt: MyType[_, _, _, _]):
pass
# Partially-bound with omitted parameters
def my_fn4(mt: MyType["Hi there!", ...]):
pass
# Unbound with omitted parameters
def my_fn5(mt: MyType):
pass
@fieldwise_init
struct MyComplicatedType[a: Int = 7, /, b: Int = 8, *, c: Int, d: Int = 9]:
pass
def my_func1(t: MyComplicatedType):
pass
def my_func2(t: MyComplicatedType[1, ...]):
pass
def my_func3(t: MyComplicatedType[1, 8, c=_, d=9]):
pass
@fieldwise_init
struct KeyWordStruct[pos_or_kw: Int, *, kw_only: Int = 10]:
pass
# Unbind both pos_or_kw and kw_only parameters
def use_kw_struct(k: KeyWordStruct[...]):
pass
def main():
# start-has-default-usage
var instance1 = UseDefault() # instance of HasDefault[10, 0]
# end-has-default-usage
_ = instance1
# start-partially-bound-example
comptime StringKeyDict = Dict[String, _]
var b: StringKeyDict[UInt8] = {"answer": 42}
# end-partially-bound-example
_ = b^
use_kw_struct(KeyWordStruct[10, kw_only=11]())
@@ -0,0 +1,48 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
# start-dependent-type-basic
def dependent_type_basic[dtype: DType, value: Scalar[dtype]]():
print("Value: ", value)
print("Value is floating-point: ", dtype.is_floating_point())
# end-dependent-type-basic
# start-dependent-type-infer-only
def dependent_type[dtype: DType, //, value: Scalar[dtype]]():
print("Value: ", value)
print("Value is floating-point: ", dtype.is_floating_point())
# end-dependent-type-infer-only
def mutate_span(span: Span[mut=True, Byte, _]) raises:
for i in range(0, len(span), 2):
if i + 1 < len(span):
span.swap_elements(i, i + 1)
def main() raises:
# start-dependent-type-basic-call
dependent_type_basic[DType.float64, Float64(2.2)]()
# end-dependent-type-basic-call
# start-dependent-type-infer-only-call
dependent_type[Float64(2.2)]()
# end-dependent-type-infer-only-call
var s = String("Robinson Crusoe surfed the interwebs.")
mutate_span(s.unsafe_as_bytes_mut())
print(s)
@@ -0,0 +1,24 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
# start-multiplier-example
def multiplier[factor: Int](x: Int) -> Int:
return x * factor
def main():
comptime times_ten = multiplier[10]
var x10 = times_ten(3)
_ = x10
# end-multiplier-example
@@ -0,0 +1,29 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
@fieldwise_init
struct Bar[v: Int]:
pass
def speak[a: Int = 3, msg: String = "woof"](bar: Bar[a]):
print(msg, a)
def use_inferred():
speak(Bar[9]()) # prints 'woof 9'
def main():
use_inferred()
@@ -0,0 +1,27 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
def speak[a: Int = 3, msg: String = "woof"]():
print(msg, a)
def use_defaults():
speak() # prints 'woof 3'
speak[5]() # prints 'woof 5'
speak[7, "meow"]() # prints 'meow 7'
speak[msg="baaa"]() # prints 'baaa 3'
def main():
use_defaults()
@@ -0,0 +1,32 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
# start-opt-and-kw-params-struct
struct KwParamStruct[greeting: String = "Hello", name: String = "🔥mojo🔥"]:
def __init__(out self):
print(Self.greeting, Self.name)
def use_kw_params():
var a = KwParamStruct[]() # prints 'Hello 🔥mojo🔥'
var b = KwParamStruct[name="World"]() # prints 'Hello World'
var c = KwParamStruct[greeting="Hola"]() # prints 'Hola 🔥mojo🔥'
# end-opt-and-kw-params-struct
_ = a^
_ = b^
_ = c^
def main():
use_kw_params()
@@ -0,0 +1,35 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
def concat[
dtype: DType, ls_size: SIMDLength, rh_size: SIMDLength, //
](lhs: SIMD[dtype, ls_size], rhs: SIMD[dtype, rh_size]) -> SIMD[
dtype, ls_size + rh_size
]:
var result = SIMD[dtype, ls_size + rh_size]()
comptime for i in range(ls_size):
result[i] = lhs[i]
comptime for j in range(rh_size):
result[ls_size + j] = rhs[j]
return result
def main():
var a = SIMD[.float32, 2](1, 2)
var x = concat(a, a)
print("result type:", x.dtype, "length:", Int(x.length))
_ = x
@@ -0,0 +1,74 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
from std.math import sqrt
# start-rsqrt-def
def rsqrt[dt: DType](x: Scalar[dt]) -> Scalar[dt]:
return 1 / sqrt(x)
# end-rsqrt-def
# start-infer-struct-param
struct One[Type: Writable & Copyable & Deinitable]:
var value: Self.Type
def __init__(out self, value: Self.Type):
self.value = value.copy()
def use_one():
var s1 = One(123) # equivalent to One[Int](123)
var s2 = One("Hello") # equivalent to One[String]("Hello")
# end-infer-struct-param
_ = s1^
_ = s2^
# start-infer-constructor-static-param
struct Two[Type: Writable & Copyable & Deinitable]:
var val1: Self.Type
var val2: Self.Type
def __init__(out self, one: One[Self.Type], another: One[Self.Type]):
self.val1 = one.value.copy()
self.val2 = another.value.copy()
print(String(self.val1), String(self.val2))
@staticmethod
def fire(thing1: One[Self.Type], thing2: One[Self.Type]):
print("🔥", String(thing1.value), String(thing2.value))
def use_two():
var s3 = Two(One("infer"), One("me"))
Two.fire(One(1), One(2))
# Two.fire(One("mixed"), One(0)) # Error: parameter inferred to two different values
# end-infer-constructor-static-param
_ = s3^
def main():
# start-rsqrt-usage
var v = Scalar[.float16](42)
print(rsqrt(v))
# end-rsqrt-usage
# second example
use_one()
# third example
use_two()
@@ -0,0 +1,21 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
def repeat[count: Int](msg: String):
comptime for i in range(count):
print(msg)
def main():
repeat[3]("Hello")
@@ -0,0 +1,76 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
from std.memory.alloc import alloc, dealloc, ThinAllocation, Layout
struct ParameterizedArray[T: Copyable & Deinitable](
Writable where conforms_to(T, Writable)
):
var _data: ThinAllocation[Self.T]
var _size: Int
def __init__(out self, var *elements: Self.T):
self._size = len(elements)
self._data = alloc[Self.T]({count = self._size}).into_thin()
var ptr = self._data.unsafe_ptr()
for i in range(self._size):
ptr.unsafe_offset(i).unsafe_write(elements[i].copy())
def __init__(out self, *, count: Int, value: Self.T):
self._size = count
self._data = alloc[Self.T]({count = count}).into_thin()
var ptr = self._data.unsafe_ptr()
for i in range(self._size):
ptr.unsafe_offset(i).unsafe_write(copy=value)
def __deinit__(deinit self):
var ptr = self._data.unsafe_ptr()
for i in range(self._size):
ptr.unsafe_offset(i).unsafe_deinit_pointee()
dealloc(self._data^.unsafe_with_layout({count = self._size}))
def __getitem__(self, i: Int) raises -> ref[self] Self.T:
if i < self._size:
return self._data.unsafe_ptr().unsafe_origin_cast[
origin_of(self)
]()[unsafe_offset=i]
else:
raise Error("Out of bounds")
def write_to(
self, mut writer: Some[Writer]
) where conforms_to(Self.T, Writable):
writer.write("[")
var ptr = self._data.unsafe_ptr()
for i in range(self._size):
writer.write(ptr[unsafe_offset=i])
if i < self._size - 1:
writer.write(", ")
writer.write("]")
@staticmethod
def splat(count: Int, value: Self.T) -> Self:
# Create a new array with count instances of the given value
return Self(count=count, value=value)
def main() raises:
# start-usage
var array = ParameterizedArray(1, 2, 3)
print(array)
# end-usage
# start-splat-usage
var float_array = ParameterizedArray[Float64].splat(8, 0)
print(float_array)
# end-splat-usage
@@ -0,0 +1,23 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
def repeat[MsgType: Writable, //, count: Int](msg: MsgType):
comptime for i in range(count):
print(msg)
def main():
# MsgType is always inferred, so first positional keyword `2` is
# passed to `count`
repeat[2](42)
@@ -0,0 +1,61 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
from std.testing import assert_true
def main() raises:
# start-basic-example
comptime AddOne[a: Int]: Int = a + 1
comptime nine = AddOne[8]
# end-basic-example
assert_true(nine == 9)
# start-function-example
def add_one(a: Int) -> Int:
return a + 1
comptime ten = add_one(9)
# end-function-example
assert_true(ten == 10)
# this example includes a an error case, and must be edited in manually.
# def return_type() -> AnyType:
# return Int # dynamic type values not permitted yet
comptime IntType = Int
# start-type-examples
comptime TwoOfAKind[dt: DType] = SIMD[dt, 2]
var twoFloats = TwoOfAKind[.float32](1.0, 2.0)
comptime StringKeyDict[ValueType: Copyable & Deinitable] = Dict[
String, ValueType
]
var b: StringKeyDict[UInt8] = {"answer": 42}
# end-type-examples
assert_true(twoFloats[0] == 1.0)
assert_true(twoFloats[1] == 2.0)
assert_true(b["answer"] == 42)
# start-floats-example
comptime Floats[size: Int, half_width: Bool = False] = SIMD[
(DType.float16 if half_width else DType.float32), size
]
var floats = Floats[2](6.0, 8.0)
var half_floats = Floats[2, True](10.0, 12.0)
# end-floats-example
assert_true(floats[0] == 6.0)
assert_true(floats[1] == 8.0)
assert_true(half_floats[0] == 10.0)
assert_true(half_floats[1] == 12.0)
@@ -0,0 +1,41 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
def slice[
dtype: DType, size: SIMDLength, //
](x: SIMD[dtype, size], offset: Int) -> SIMD[dtype, size // 2]:
comptime new_size = size // 2
var result = SIMD[dtype, new_size]()
for i in range(new_size):
result[i] = Scalar[dtype](x[i + offset])
return result
def reduce_add(x: SIMD) -> Int:
comptime if x.length == 1:
return Int(x[0])
elif x.length == 2:
return Int(x[0]) + Int(x[1])
# Extract the top/bottom halves, add them, sum the elements.
comptime half_size = x.length // 2
var lhs = slice(x, 0)
var rhs = slice(x, half_size)
return reduce_add(lhs + rhs)
def main():
var x = SIMD[.int, 4](1, 2, 3, 4)
print(x)
print("Elements sum:", reduce_add(x))
@@ -0,0 +1,25 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
def take_simd8(x: SIMD[DType.float32, 8]):
pass
def generic_simd[nelts: SIMDLength](x: SIMD[DType.float32, nelts]):
comptime if nelts == 8:
take_simd8(rebind[SIMD[DType.float32, 8]](x))
def main():
generic_simd(SIMD[DType.float32, 8](1))
@@ -0,0 +1,27 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
# start-rsqrt-example
from std.math import sqrt
def rsqrt[dt: DType](x: Scalar[dt]) -> Scalar[dt]:
return 1 / sqrt(x)
def main() raises:
var v = Scalar[.float16](42)
print(rsqrt(v))
# end-rsqrt-example
@@ -0,0 +1,45 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
struct Circle[radius: Float64]:
comptime pi = 3.14159265359
comptime circumference = 2.0 * Self.pi * Self.radius
# start-reference-parameter-on-type
def on_type():
print(Int(SIMD[DType.float32, 2].length)) # prints 2
# end-reference-parameter-on-type
# start-reference-parameter-on-instance
def on_instance():
var x = SIMD[.int32, 2](4, 8)
print(x.dtype) # prints int32
# end-reference-parameter-on-instance
_ = x
def slice_example():
# start-simd-slice-example
var m = SIMD[.int32, 4](1, 3, 5, 7)
var n = m.slice[2]()
print(n) # prints [1, 3]
# end-simd-slice-example
def main():
on_type()
on_instance()
slice_example()
@@ -0,0 +1,59 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
def main():
var vector = SIMD[.int16, 4](1, 2, 3, 4)
vector = vector * vector
for i in range(4):
print(vector[i], end=" ")
print()
# Example: "Using parameterized types and functions"
# start-simd-usage-example
# Make a vector of 4 floats.
var small_vec = SIMD[.float32, 4](1.0, 2.0, 3.0, 4.0)
# Make a big vector containing 1.0 in float16 format.
var big_vec = SIMD[.float16, 32](1.0)
# Do some math and convert the elements to float32.
var bigger_vec = (big_vec + big_vec).cast[.float32]()
# You can write types out explicitly if you want of course.
var bigger_vec2: SIMD[DType.float32, 32] = bigger_vec
print("small_vec DType:", small_vec.dtype, "length:", Int(small_vec.length))
print(
"bigger_vec2 DType:",
bigger_vec2.dtype,
"length:",
Int(bigger_vec2.length),
)
# end-simd-usage-example
# second example
from std.math import sqrt
def rsqrt[
dt: DType, width: SIMDLength
](x: SIMD[dt, width]) -> SIMD[dt, width]:
return 1 / sqrt(x)
var v = SIMD[.float16, 4](42)
print(rsqrt(v))
_ = small_vec
_ = bigger_vec2
@@ -0,0 +1,30 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
struct MyTensor[*dimensions: Int]:
pass
def sum_params[*values: Int]() -> Int:
var sum = 0
for v in values:
sum += v
return sum
comptime sum = sum_params[1, 2, 3, 4, 5]()
def main():
print(sum)
@@ -0,0 +1,23 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
from std.memory import ArcPointer
def main():
# start-arc-pointer-create
var attributesDict: Dict[String, String] = {}
var attributes = ArcPointer(attributesDict^)
# end-arc-pointer-create
_ = attributes
@@ -0,0 +1,28 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
from std.memory import OwnedPointer
def main():
# start-owned-pointer-create
var ptr: OwnedPointer[Int]
ptr = OwnedPointer(100)
# end-owned-pointer-create
# start-owned-pointer-dereference
# Update an initialized value
ptr[] += 10
# Access an initialized value
print(ptr[])
# end-owned-pointer-dereference
@@ -0,0 +1,30 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
from std.memory import Pointer
def main():
var some_value: Int = 42
# start-pointer-create
var ptr = Pointer(to=some_value)
# end-pointer-create
print(ptr[])
# Pointers can be copied
# start-pointer-copy
var copied_ptr = ptr
# end-pointer-copy
print(copied_ptr[])
@@ -0,0 +1,38 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
from std.memory import ArcPointer
struct SharedDict(ImplicitlyCopyable):
var attributes: ArcPointer[Dict[String, String]]
def __init__(out self):
var attributesDict: Dict[String, String] = {}
self.attributes = ArcPointer(attributesDict^)
def __init__(out self, *, copy: Self):
self.attributes = copy.attributes
def __setitem__(mut self, key: String, value: String):
self.attributes[][key] = value
def __getitem__(self, key: String) -> String:
return self.attributes[].get(key, default="")
def main():
var thing1 = SharedDict()
var thing2 = thing1
thing1["Flip"] = "Flop"
print(thing2["Flip"])
@@ -0,0 +1,89 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
from std.memory.alloc import alloc, dealloc, ThinAllocation, Layout
from std.testing import assert_equal
def inline_allocation() raises:
# Include following line uncommented
# from std.memory.alloc import alloc, dealloc, Layout
var allocation = alloc(Layout[Int](count=4))
# Use allocation
var ptr = allocation.unsafe_ptr()
for i in range(4):
ptr.unsafe_offset(i).unsafe_write(i)
# Omit next line
var tmp = ptr[unsafe_offset=3]
# Release allocation
dealloc(allocation^)
# Delay assert until after allocation is released
assert_equal(tmp, 3)
def raising_function(ptr: Pointer[Float64, _]) raises:
pass
def allocating_function() raises:
var data = alloc[Float64]({count = 64})
# ...
try:
raising_function(data.unsafe_ptr())
except e:
dealloc(data^)
raise e^ # propagate the error
dealloc(data^)
def leaky_function() raises:
var data_ptr = alloc[Float64]({count = 64}).unsafe_leak()
# ...
raising_function(data_ptr)
dealloc(
ThinAllocation(unsafe_owned_ptr=data_ptr).unsafe_with_layout(
{count = 64}
)
)
struct Counter:
comptime _layout = Layout[Int].single()
var _alloc: ThinAllocation[Int]
def __init__(out self, value: Int):
self._alloc = alloc(Self._layout).into_thin()
self._alloc.unsafe_ptr().unsafe_write(value)
def increment(mut self):
self._alloc.unsafe_ptr()[] += 1
def get(self) -> Int:
return self._alloc.unsafe_ptr()[]
def __deinit__(deinit self):
# Convert ThinAllocation back into Allocation
dealloc(self._alloc^.unsafe_with_layout(Self._layout))
def use_counter() raises:
var c = Counter(0)
c.increment()
c.increment()
assert_equal(c.get(), 2)
def main() raises:
inline_allocation()
use_counter()
allocating_function()
leaky_function()
@@ -0,0 +1,98 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
from std.memory.alloc import alloc, dealloc, Layout
def test_intro():
# start-safe-example
var count: Int = 0
# Point to an existing value
var ptr = Pointer(to=count) # ptr's type is Pointer[Int, ...]
# Mutate the value
ptr[] = 100
# end-safe-example
def test_basics():
# Allocate memory to hold a value
# start-basics-alloc
var allocation = alloc(Layout[Int].single())
var ptr = allocation.unsafe_ptr()
# end-basics-alloc
# Initialize the allocated memory
ptr.unsafe_write(100)
# start-dereference
# Update an initialized value
ptr[] += 10
# Access an initialized value
print(ptr[])
# end-dereference
dealloc(allocation^)
def test_pointer_to_value():
# start-pointer-to-value
var counter: Int = 5
var ptr = Pointer(to=counter)
# end-pointer-to-value
# start-dereference-read-mutate
# Read from pointee
print(ptr[])
# Mutate pointee
ptr[] = 0
# end-dereference-read-mutate
def test_alloc_string():
# start-alloc-string
var allocation = alloc[String]({count = 1})
var str_ptr = allocation.unsafe_ptr()
# str_ptr[] = "Testing" # Undefined behavior!
str_ptr.unsafe_write("Testing")
str_ptr[] += " pointers" # Works now
# end-alloc-string
str_ptr.unsafe_deinit_pointee()
dealloc(allocation^)
def test_unsafe_write_owned():
var allocation = alloc[String]({count = 1})
var str_ptr = allocation.unsafe_ptr()
# start-unsafe-write-owned
str_ptr.unsafe_write("Owned string")
# end-unsafe-write-owned
str_ptr.unsafe_deinit_pointee()
dealloc(allocation^)
def test_pointer_to_string():
# start-pointer-to-string
var s = "Testing"
var s_ptr = Pointer(to=s)
# end-pointer-to-string
_ = s_ptr
def main():
test_intro()
test_basics()
test_pointer_to_value()
test_alloc_string()
test_unsafe_write_owned()
test_pointer_to_string()
@@ -0,0 +1,78 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
from std.bit import byte_swap
from std.memory.alloc import alloc, dealloc, Layout
# start-read-chunks
def read_chunks(
var ptr: Pointer[mut=False, UInt8, _],
) -> List[List[UInt32]]:
var chunks = List[List[UInt32]]()
# A chunk size of 0 indicates the end of the data
var chunk_size = Int(ptr[])
while chunk_size > 0:
# Skip the 1 byte chunk_size and get a pointer to the first
# UInt32 in the chunk
var ui32_ptr = ptr.unsafe_offset(1).unsafe_bitcast[UInt32]()
var chunk = List[UInt32](capacity=chunk_size)
for i in range(chunk_size):
chunk.append(ui32_ptr[unsafe_offset=i])
# List is not implicitly copyable, so it needs the transfer sigil (^)
chunks.append(chunk^)
# Move our pointer to the next byte after the current chunk
ptr = ptr.unsafe_offset(1 + 4 * chunk_size)
# Read the size of the next chunk
chunk_size = Int(ptr[])
return chunks^
# end-read-chunks
def main():
# Build a test buffer: 2 chunks.
# Chunk 1: size=2, values=[10, 20] (as UInt32 little-endian)
# Chunk 2: size=1, values=[30]
# Terminator: size=0
var allocation = alloc(Layout[UInt8](count=1 + 8 + 1 + 4 + 1))
var buf = allocation.unsafe_ptr()
var offset = 0
# Chunk 1 header
buf.unsafe_offset(offset).unsafe_write(UInt8(2))
offset += 1
# Chunk 1 values (little-endian UInt32)
buf.unsafe_offset(offset).unsafe_bitcast[UInt32]().unsafe_write(UInt32(10))
offset += 4
buf.unsafe_offset(offset).unsafe_bitcast[UInt32]().unsafe_write(UInt32(20))
offset += 4
# Chunk 2 header
buf.unsafe_offset(offset).unsafe_write(UInt8(1))
offset += 1
# Chunk 2 value
buf.unsafe_offset(offset).unsafe_bitcast[UInt32]().unsafe_write(UInt32(30))
offset += 4
# Terminator
buf.unsafe_offset(offset).unsafe_write(UInt8(0))
var result = read_chunks(buf)
print(len(result)) # 2
print(result[0][0]) # 10
print(result[0][1]) # 20
print(result[1][0]) # 30
dealloc(allocation^)
@@ -0,0 +1,39 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
# start-unsafe-from-address
def write_to_address(mmio_address: Int, value: Int32):
var ptr = Pointer[Int32, MutUntrackedOrigin](
unsafe_from_address=mmio_address
)
# Writing to a raw memory address may require a volatile load/store as the
# operation may have side effects not visible to the compiler.
# You can specify this using the `volatile` parameter.
ptr.unsafe_store[volatile=True](value)
# end-unsafe-from-address
def main():
# Test opaque pointer creation via bitcast.
# start-opaque-pointer
var str = "Hello, world!"
var str_ptr = Pointer(to=str)
var opaque_ptr = str_ptr.unsafe_bitcast[NoneType]()
# ... call some foreign function that takes a void pointer
# end-opaque-pointer
_ = opaque_ptr
@@ -0,0 +1,50 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
from std.memory.alloc import alloc, dealloc, Layout
def main():
# start-alloc-multiple
var allocation = alloc(Layout[Float64](count=6))
var float_ptr = allocation.unsafe_ptr()
for offset in range(6):
float_ptr.unsafe_offset(offset).unsafe_write(0.0)
# end-alloc-multiple
# start-subscript-access
float_ptr[unsafe_offset=2] = 3.0
for offset in range(6):
print(float_ptr[unsafe_offset=offset], end=", ")
# end-subscript-access
print()
# Pointer arithmetic: offset from an existing pointer
var first_ptr = float_ptr
# start-pointer-offset
var third_ptr = first_ptr.unsafe_offset(2)
# end-pointer-offset
print(third_ptr[])
# Advance a pointer to the next element
var ptr = float_ptr
# start-pointer-advance
# Advance the pointer one element:
ptr = ptr.unsafe_offset(1)
# end-pointer-advance
print(ptr[])
for offset in range(6):
float_ptr.unsafe_offset(offset).unsafe_deinit_pointee()
dealloc(allocation^)
@@ -0,0 +1,49 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
from std.memory.alloc import alloc, dealloc, Layout, ThinAllocation
def test_unsafe_dangling():
# start-unsafe-dangling
var ptr = Pointer[Int, MutUntrackedOrigin].unsafe_dangling()
# end-unsafe-dangling
_ = ptr
def main():
# start-optional-pointer
var ptr = Optional[Pointer[Int, MutUntrackedOrigin]]()
# end-optional-pointer
# Optional is initially None; if block is skipped.
if ptr:
# ptr is not None — safe to unwrap
var p = ptr.value()
print(p[])
# Assign a real value to test the non-None path. The `Optional` holds an
# untracked raw pointer, so leak the allocation and pair the pointer back
# with its layout to release it.
comptime layout = Layout[Int].single()
var x_ptr: Pointer[Int, MutUntrackedOrigin] = alloc(layout).unsafe_leak()
x_ptr.unsafe_write(42)
ptr = x_ptr
if ptr:
# ptr is not None — safe to unwrap
var p = ptr.value()
print(p[])
x_ptr.unsafe_deinit_pointee()
dealloc(ThinAllocation(unsafe_owned_ptr=x_ptr).unsafe_with_layout(layout))
test_unsafe_dangling()
Loaded 100 of 1567 files, more files were not shown because too many files have changed in this diff. Show more