Initial commit
Test (in pplus-core) / in-core (push) Failing after 28m44s

This commit is contained in:
alexm committed 2026-11-12 22:23:48 -05:00
commit 568474d52f
1591 files changed
+528213

No files matched your search

@@ -0,0 +1,271 @@
# ===----------------------------------------------------------------------=== #
# 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 for the Mojo "Basics" cheat-sheet card.
The module docstring itself exercises the Comments & docstrings panel.
"""
# Not tested (compile-time errors: a runtime test cannot assert that code
# FAILS to compile; these are verified by hand and belong in a lit
# expected-error test if we want them automated):
# - no implicit numeric conversion: `var f: Float64 = i` (i: Int) must error
# - a bare bracket literal is an `Array`, so `[1, 2, 3].append(4)` must error
# - `SIMD` width must be a power of two: `SIMD[DType.float32, 3]` must error
#
# Not tested (outside a runtime test's reach):
# - `mojo build hello.mojo` creates a `hello` executable
# - `print()` output formatting (asserted through `String(...)` instead,
# which shares the same `sep` keyword)
from std.math import sqrt
from std.math import sqrt as root
from std.testing import assert_equal, assert_false, assert_true
def risky() raises:
raise Error("boom")
def add_two(a: Int, b: Int) -> Int:
return a + b
def sign(x: Int) -> String:
if x > 0:
return "positive"
elif x == 0:
return "zero"
else:
return "negative"
def describe(x: Int) -> String:
match x:
case 2:
return "is exactly two"
case _ if x.is_power_of_two():
return "power of two"
case _:
return "not power of two"
@fieldwise_init
struct Point:
var x: Int
var y: Int
struct Counter:
comptime START = 0
var n: Int
def __init__(out self):
self.n = Self.START
def bump(mut self):
self.n += 1
@staticmethod
def origin() -> Point:
return Point(0, 0)
def test_ref_writes_through() raises:
var data: List = [1, 2, 3]
ref view = data[0]
view = 99
assert_equal(data[0], 99)
def test_number_types() raises:
var f: SIMD[DType.float32, 1] = Float32(1.5)
var s: Scalar[DType.float32] = f
assert_equal(s, 1.5)
# Dot notation must name the same type as the spelled-out `DType` form,
# or this assignment fails to compile.
var v: SIMD[DType.float32, 8] = SIMD[.float32, 8](2.0)
assert_equal(v.reduce_add(), 16.0)
def test_conversions() raises:
var i = 42
assert_equal(Float64(i), 42.0)
assert_equal(Int(Float64(2.9)), 2)
assert_equal(String(i), "42")
assert_equal(SIMD[DType.int32, 4](7).cast[DType.float32]()[0], 7.0)
def test_operators() raises:
assert_equal(2**10, 1024)
assert_equal(pow(2, 10), 1024)
assert_equal(7 // 2, 3)
assert_equal(7 % 2, 1)
var a = 1
var b = 2
var c = 2
assert_true(a < b <= c)
assert_false(a < b < c)
def test_other_types() raises:
var arr = [1, 2, 3]
# Only compiles if the bare literal inferred `Array[Int, 3]`.
var fixed: Array[Int, 3] = arr^
assert_equal(len(fixed), 3)
def test_strings() raises:
var who = "Mojo"
assert_equal("Hi, " + who, "Hi, Mojo")
assert_equal(String(t"Hi, {who}!"), "Hi, Mojo!")
assert_equal(String(1, 2, 3, sep=": "), "1: 2: 3")
assert_equal(String(t"x = {1 + 1}"), "x = 2")
var raw = r"C:\path"
assert_equal(raw.byte_length(), 7)
def test_control_flow() raises:
assert_equal(sign(5), "positive")
assert_equal(sign(0), "zero")
assert_equal(sign(-5), "negative")
# 2 also satisfies the power-of-two guard, so this pins first-match order.
assert_equal(describe(2), "is exactly two")
assert_equal(describe(8), "power of two")
assert_equal(describe(6), "not power of two")
var x = 3
var kind = "even" if x % 2 == 0 else "odd"
assert_equal(kind, "odd")
def test_loops() raises:
var seen: List[Int] = []
for item in [10, 20, 30]:
if item == 20:
continue
if item == 30:
break
seen.append(item)
assert_equal(len(seen), 1)
assert_equal(seen[0], 10)
var countdown: List[Int] = []
var n = 4
while n > 0:
countdown.append(n)
n -= 1
assert_equal(countdown, [4, 3, 2, 1])
def test_functions() raises:
assert_equal(add_two(2, 3), 5)
var c = 10
def add_c(a: Int) {imm c} -> Int:
return a + c
assert_equal(add_c(5), 15)
var anon = lambda (a: Int) {imm c} -> Int: a + c
assert_equal(anon(10), 20)
def test_imports() raises:
assert_equal(sqrt(16.0), 4.0)
assert_equal(root(16.0), 4.0)
def test_list_ops() raises:
var xs: List = [1, 2, 3]
xs.append(4)
assert_equal(xs[0], 1)
assert_equal(len(xs), 4)
def test_dict_ops() raises:
var xs: Dict = {"a": 1, "b": 2}
xs["c"] = 3
assert_equal(xs.get("a", 0), 1)
assert_equal(xs.get("d", 0), 0)
assert_equal(len(xs), 3)
var raised = False
try:
_ = xs["d"]
except:
raised = True
assert_true(raised)
def test_structs() raises:
var p = Point(3, 4)
assert_equal(p.x, 3)
assert_equal(p.y, 4)
var counter = Counter()
counter.bump()
assert_equal(counter.n, 1)
assert_equal(Counter.START, 0)
assert_equal(Counter.origin().x, 0)
def test_errors_try_except() raises:
var caught = String("")
try:
risky()
except e:
caught = String(e)
assert_equal(caught, "boom")
def test_explicit_copy() raises:
var a: List[Int] = [1, 2]
var b = a.copy()
b.append(3)
assert_equal(len(a), 2)
assert_equal(len(b), 3)
def test_paren_line_continuation() raises:
# fmt: off
var total = (1 +
2 +
3)
# fmt: on
assert_equal(total, 6)
def test_semicolons() raises:
# fmt: off
var a = 1; a += 1
# fmt: on
assert_equal(a, 2)
def main() raises:
test_ref_writes_through()
test_number_types()
test_conversions()
test_operators()
test_other_types()
test_strings()
test_control_flow()
test_loops()
test_functions()
test_imports()
test_list_ops()
test_dict_ops()
test_structs()
test_errors_try_except()
test_explicit_copy()
test_paren_line_continuation()
test_semicolons()
@@ -0,0 +1,297 @@
# ===----------------------------------------------------------------------=== #
# 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_compile_time.mojo
# Tests for the Mojo "compile-time" cheat-sheet card.
#
# Exercises the card's claims so one that drifts stops compiling or fails an
# assert: parameters, where clauses (with messages and on thin function
# types), trait bounds, running a function at compile time, literal
# precision, comptime if/for, sys.info queries with a
# CompilationTarget, comptime members, and the inlining decorators, including
# inlining chosen by a parameter.
#
# Not tested (no portable assertable value, or a compile error can't be
# asserted at runtime):
# - reflect[T] field surface beyond .name(): newly introduced and documented
# as incomplete; the wider field API may still shift.
# - 2**200: overflows a 64-bit Int, so it can't be materialized to compare.
# - comptime if on hardware facts (is_nvidia_gpu, ...): machine-dependent.
# - CompilationTarget.default_accelerator(): fails to instantiate on a host
# with no accelerator configured.
# - where messages: they appear only in compile errors.
# - the compile-time boundary (no file I/O, no raising, runs on CPU): these
# are compile errors, which a runtime test can't assert.
from std.testing import assert_equal
from std.sys.info import size_of, align_of, simd_width_of
from std.sys.info import CompilationTarget
from std.builtin.globals import global_constant
# --- parameters: a value parameter and a type parameter ---
def scaled[factor: Int](x: Int) -> Int:
return x * factor # factor is a compile-time value parameter
def pick[T: Copyable](a: T, b: T, take_first: Bool) -> T:
return a.copy() if take_first else b.copy() # T is a type parameter
def test_parameters() raises:
assert_equal(scaled[3](10), 30)
assert_equal(pick[Int](1, 2, True), 1)
# --- where: gate on a numeric truth ---
def block[
w: Int
]() -> Int where w.is_power_of_two() else ("'w' must be a power of two"):
return w # only callable when w is a power of two
# A thin function type carries the constraint; every bound function must too.
comptime Kernel = def[w: Int](Int) thin -> Int where w > 0 else (
"'w' must be positive"
)
def times[w: Int](x: Int) -> Int where w > 0 else "'w' must be positive":
return x * w
def apply[F: Kernel](x: Int) -> Int:
return F[4](x)
# The type exists for every DType; average() exists only for numeric ones.
@fieldwise_init
struct Values[dtype: DType]:
var a: Scalar[Self.dtype]
var b: Scalar[Self.dtype]
def average(self) -> Float64 where Self.dtype.is_numeric():
return (Float64(self.a) + Float64(self.b)) / 2
def test_where() raises:
assert_equal(block[8](), 8)
assert_equal(apply[times](3), 12)
assert_equal(Values[DType.int32](3, 4).average(), 3.5)
_ = Values[DType.bool](True, False) # constructs, but has no average()
# --- conformances: a trait bound admits only proven operations ---
def largest[T: Comparable & Copyable & Deinitable](xs: List[T]) -> T:
var best_i = 0
for i in range(len(xs)):
if xs[i] > xs[best_i]:
best_i = i
return xs[best_i].copy()
def test_conformances() raises:
assert_equal(largest([3, 1, 4, 1, 5]), 5)
# --- run code at compile time: any function, no marker ---
def square(x: Int) -> Int:
return x * x
def test_run_at_compile_time() raises:
comptime nine = square(3) # square runs while compiling
assert_equal(nine, 9)
# --- numeric precision: literals stay exact, Float64 rounds ---
def test_numeric_precision() raises:
comptime c = 0.1 + 0.2 # folded exactly as a literal
assert_equal(c == 0.3, True)
var a = 0.1 # a Float64 now
var r = a + 0.2
assert_equal(r == 0.3, False) # 0.30000000000000004
# --- query the target ---
def test_query_target() raises:
assert_equal(size_of[Int32](), 4)
assert_equal(size_of[Int64](), 8)
assert_equal(align_of[Int32](), 4)
comptime host = CompilationTarget.current() # an explicit target
assert_equal(size_of[Int64, host](), 8)
assert_equal(
simd_width_of[DType.float32, host](), simd_width_of[DType.float32]()
)
# --- comptime members live on types ---
struct Stack[T: Copyable]:
comptime Element = Self.T # associated type (reached through Self)
comptime capacity = 1024 # a compile-time value member
def test_comptime_members() raises:
assert_equal(Stack[Int].capacity, 1024)
var e: Stack[Int].Element = 5 # Element resolves to Int for Stack[Int]
assert_equal(e, 5)
# --- comptime for: fully unrolled, index is a constant ---
def test_comptime_for() raises:
var total = 0
comptime for i in range(4):
total += i # 0 + 1 + 2 + 3
assert_equal(total, 6)
# --- comptime if: only the live branch is kept ---
def test_comptime_if() raises:
var width: Int
comptime if size_of[Int64]() == 8:
width = 64 # the live branch (condition is known)
else:
width = 0
assert_equal(width, 64)
# --- inlining: force or forbid ---
@inline(.always)
def add_inline(a: Int, b: Int) -> Int:
return a + b
@inline(.never)
def add_separate(a: Int, b: Int) -> Int:
return a + b
@inline(.automatic)
def add_auto(a: Int, b: Int) -> Int:
return a + b
@inline(.nodebug)
def add_nodebug(a: Int, b: Int) -> Int:
return a + b
# --- inline by parameter: each instantiation chooses ---
@inline(policy)
def doubled[policy: InlineLevel](x: Int) -> Int:
return x * 2
def test_inlining() raises:
assert_equal(add_inline(2, 3), 5)
assert_equal(add_separate(2, 3), 5)
assert_equal(add_auto(2, 3), 5)
assert_equal(add_nodebug(2, 3), 5)
assert_equal(doubled[.always](3), 6)
assert_equal(doubled[.never](3), 6)
# --- comptime match: specialize by pattern ---
def small_tile[mt: Int, nt: Int]() -> String where mt * nt <= 256:
return String("small ", mt, "x", nt)
def tile_path[m: Int, n: Int]() -> String:
comptime match (m, n):
case (16, 16):
return "tuned 16x16"
case (mt, nt) if mt * nt <= 256: # the guard proves small_tile's where
return small_tile[mt, nt]()
case _:
return "generic"
def tile_count[m: Int]() -> Int:
var hits = 0
comptime match m:
case 16:
hits += 1
# no case _: an unmatched subject compiles to nothing
return hits
def test_comptime_match() raises:
assert_equal(tile_path[16, 16](), "tuned 16x16")
assert_equal(tile_path[8, 4](), "small 8x4")
assert_equal(tile_path[64, 64](), "generic")
assert_equal(tile_count[16](), 1)
assert_equal(tile_count[64](), 0)
# --- conditional availability: a method exists only when its condition holds ---
@fieldwise_init
struct Buf[n: Int]:
var value: Int
def first(self) -> Int where Self.n > 0: # exists only when n > 0
return self.value
def test_conditional_availability() raises:
var b = Buf[3](42)
assert_equal(b.first(), 42)
# --- type_of: capture the type of an expression ---
def test_type_of() raises:
var x = 5
var y: type_of(x) = x + 5 # type_of(x) is Int
assert_equal(y, 10)
# --- conditional construction: default-construct only when proven ---
def test_conditional_construction() raises:
var x = 0
comptime if conforms_to(type_of(x), Defaultable):
var y = type_of(x)() # the default constructor (no make_default)
assert_equal(y, x) # both 0
# --- reflect: read a type's name ---
def test_reflect() raises:
comptime name = reflect[Int].name()
# Int unifies with SIMD, so its reflected name is the SIMD spelling.
assert_equal(String(name), "SIMD[DType.int, 1]")
# --- materialization: comptime value -> runtime ---
comptime POWERS: Array[Int, 4] = [1, 2, 4, 8]
def test_materialization() raises:
comptime table: List[Int] = [3, 5, 7, 11, 13]
var t = materialize[table]() # heap-backed comptime List -> runtime List
assert_equal(t[1], 5)
ref g = global_constant[POWERS]() # static table, indexed without a copy
assert_equal(g[2], 4)
def main() raises:
test_parameters()
test_where()
test_conformances()
test_run_at_compile_time()
test_numeric_precision()
test_query_target()
test_comptime_members()
test_comptime_for()
test_comptime_if()
test_inlining()
test_conditional_availability()
test_type_of()
test_conditional_construction()
test_reflect()
test_materialization()
@@ -0,0 +1,412 @@
# ===----------------------------------------------------------------------=== #
# 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_conversions.mojo
# Tests for the Mojo "conversions" cheat-sheet card.
#
# Exercises the make / convert / access casts shown on the card so a claim that
# drifts stops compiling or fails an assert.
#
# Not tested (need a GPU/Python, or no portable runtime API to assert):
# - .value()/.take() on an empty Optional abort (can't assert an abort)
# - @implicit conversions (a compile-time behavior, not a runtime value)
# - conversions that don't compile (Int16(s), Float32 from a Floatable,
# mixed-width arithmetic): compile errors can't be asserted at runtime
# - Python conversions (need the Python runtime); Float8 (needs a GPU)
from std.ffi import external_call
from std.memory import bitcast, dealloc
from std.reflection import reflect
from std.sys.info import size_of
from std.testing import assert_equal, assert_true, assert_false, assert_raises
# A user type joins T(x) conversion by conforming to the conversion traits.
@fieldwise_init
struct Celsius(Boolable, Floatable, Intable, Writable):
var deg: Float64
def __float__(self) -> Float64:
return self.deg
def __int__(self) -> Int:
return Int(self.deg)
def __bool__(self) -> Bool:
return self.deg != 0
def write_to(self, mut w: Some[Writer]):
w.write(self.deg, "C")
def test_establishing_types() raises:
# explicit typing from literal expressions
assert_equal(Int(32), 32)
assert_equal(Int16(32), 32)
# new forms across types
var f: Float64 = 3.9
var i: Int = 7
assert_equal(Int64(f), 3)
assert_equal(Float64(i), 7.0)
assert_equal(String(i), "7")
# the trait table: Intable reaches any integer type, Floatable only Float64
var c = Celsius(21.5)
assert_equal(Int16(c), 21)
assert_equal(UInt8(c), 21)
assert_equal(Float64(c), 21.5)
assert_true(Bool(c))
assert_equal(String(c), "21.5C")
# strings convert only to Int and Float64; go through one, then narrow
var s = String("12")
assert_equal(Int(s), 12)
assert_equal(Float64(s), 12.0)
assert_equal(Int16(Int(s)), 12)
with assert_raises():
_ = Int(String("two"))
def test_casting() raises:
# same-width signed/unsigned keeps the bits
assert_equal(UInt(Int(-1)), UInt.MAX)
var f64: Float64 = 1.0
var f32: Float32 = 1.0
var i32: Int32 = 2
assert_equal(f64.cast[.int32](), 1) # convert the value
assert_equal(bitcast[.uint32](f32), 1065353216) # reinterpret the bits
assert_equal(f64 + Float64(i32), 3.0) # explicit, never implicit
assert_equal(Float64(f32) + f64, 2.0) # widen one side to match
# widening preserves precision; narrowing may lose it
var tenth: Float32 = 0.1
assert_equal(Float64(tenth).cast[.float32](), tenth)
assert_true(Float64(Float64(0.1).cast[.float32]()) != 0.1)
def test_numbers() raises:
# make an Int: from Intable, a scalar, a String (raising)
assert_equal(Int(True), 1)
assert_equal(Int(Int32(5)), 5)
assert_equal(Int("42"), 42)
# Int is a SIMD scalar, so .cast works
assert_equal(Int(5).cast[.int8](), Int8(5))
# Int <-> UInt share bits: the reinterpretation round-trips
assert_equal(Int(UInt(Int(-1))), -1)
# make a Float64; Float -> Int truncates toward zero
assert_equal(Float64(3), 3.0)
assert_equal(Float64("1.5"), 1.5)
assert_equal(Int(Float64(3.9)), 3)
# Bool: from Boolable, from None
assert_true(Bool(1))
assert_true(Bool("x"))
assert_false(Bool(""))
assert_false(Bool(None))
# number -> Bool / Float / String
assert_equal(Int(True), 1)
assert_equal(Int(False), 0)
assert_equal(Float64(True), 1.0)
assert_equal(String(True), "True")
def test_numeric_creation() raises:
var int_default = 42 # integer literals default to Int
var float_default = 3.14 # floating-point literals default to Float64
assert_equal(
String(reflect[type_of(int_default)].name()),
String(reflect[Int].name()),
)
assert_equal(
String(reflect[type_of(float_default)].name()),
String(reflect[Float64].name()),
)
assert_true(int_default == 42 and float_default > 3.0)
assert_true(Float16(3.14) > 3.1) # a literal takes the type you name
assert_equal(size_of[Float64](), 8) # Float64 is always 64 bits
assert_equal(size_of[Int](), size_of[OpaquePointer[MutUntrackedOrigin]]())
var i32 = Int32(42) # a literal becomes the type you name
var f32 = Float32(3.14)
assert_equal(i32, 42)
assert_true(f32 > 3.13 and f32 < 3.15)
var c = Celsius(21.5)
assert_equal(Int32(c), 21) # any Intable, to any integer dtype
assert_equal(Float64(c), 21.5) # any Floatable; Float64 only
with assert_raises():
_ = Int("two")
with assert_raises():
_ = Float64("two")
def test_numeric_conversion() raises:
var fp64: Float64 = 3.9
assert_equal(fp64.cast[DType.int32](), 3) # .cast works on Float64
assert_equal(Int(300).cast[DType.int8](), 44) # integer casts wrap
assert_equal(Float64(-2.5).cast[DType.int32](), -2) # toward zero
assert_equal(UInt(Int(-1)), UInt.MAX) # same bits
assert_equal(Float64(7), 7.0)
assert_equal(String(42), "42")
assert_true(Bool(3))
assert_false(Bool(0.0))
var narrow = Float64(0.1).cast[DType.float32]()
assert_true(Float64(narrow) != 0.1) # precision loss
def test_simd() raises:
var v = SIMD[.int32, 4](7) # splat one value to all lanes
assert_equal(v.reduce_add(), 28)
var v2 = SIMD[.int32, 4](1, 2, 3, 4) # per-lane (N matches arg count)
assert_equal(v2[2], 3)
assert_equal(v2.cast[.float64]()[0], 1.0) # new dtype, same lane count
var s: Int32 = 9
assert_equal(SIMD[.int32, 4](s).reduce_add(), 36) # scalar -> splat
def test_string() raises:
# make from any Writable
assert_equal(String(42), "42")
assert_equal(String(True), "True")
# convert: parse
assert_equal(Int("7"), 7)
assert_equal(Float64("2.5"), 2.5)
assert_true(Bool("x"))
assert_false(Bool(String("")))
# access: byte/codepoint index + slice; grapheme single-index only
var s = String("abcde")
assert_equal(s[byte=0], "a")
assert_equal(s[byte=1:3], "bc")
assert_equal(s[codepoint=1], "b")
assert_equal(s[codepoint=1:3], "bc")
assert_equal(s[grapheme=2], "c")
# as_bytes is a byte Span; codepoints and graphemes are iterators
assert_equal(len(String("abc").as_bytes()), 3)
var cps = 0
for _ in String("héllo").codepoints():
cps += 1
assert_equal(cps, 5)
var gs = 0
for _ in String("héllo").graphemes():
gs += 1
assert_equal(gs, 5)
def test_parse_failures() raises:
# Int(s) raises on a float, hex, empty, or out-of-range string
with assert_raises():
_ = Int("3.5")
with assert_raises():
_ = Int("0xff")
with assert_raises():
_ = Int("")
with assert_raises():
_ = Int("9223372036854775808") # Int.MAX + 1
# Float64(s) accepts exponents and inf, raises on empty or garbage
assert_equal(Float64("1e3"), 1000.0)
assert_equal(Float64("inf"), Float64.MAX * 2) # overflows to +inf
with assert_raises():
_ = Float64("")
with assert_raises():
_ = Float64("garbage")
def test_utf8() raises:
var bad: List[Byte] = [0x68, 0xFF, 0x69] # "h", an invalid byte, "i"
with assert_raises():
_ = String(from_utf8=Span(bad))
var lossy = String(from_utf8_lossy=Span(bad)) # bad byte -> U+FFFD
assert_equal(lossy, "h\uFFFDi")
assert_equal(String(from_utf8="héllo".as_bytes()), "héllo")
def test_pointers() raises:
# reach into a container's raw buffer, then vectorize it (the escape hatch)
var r = List(range(4))
var vec = r.unsafe_ptr().unsafe_load[width=4]() # 4 elements -> one SIMD
assert_equal(vec.reduce_add(), 6) # 0+1+2+3
assert_equal(r.unsafe_ptr()[unsafe_offset=0], 0) # deref one element
assert_equal(r.unsafe_ptr().unsafe_offset(2)[], 2) # arithmetic, then deref
var none = OptionalPointer[Int, MutUntrackedOrigin]() # nullable pointer
assert_false(Bool(none))
def test_collection_literals() raises:
var arr = [1, 2, 3] # unannotated brackets make an Array
assert_equal(
String(reflect[type_of(arr)].name()),
String(reflect[Array[Int, 3]].name()),
)
assert_equal(arr[0], 1)
var lst: List = [1, 2, 3] # annotate to get a List
assert_equal(
String(reflect[type_of(lst)].name()), String(reflect[List[Int]].name())
)
assert_equal(len(lst), 3)
var d = {"a": 1, "b": 2} # unannotated braces make a Dict
assert_equal(
String(reflect[type_of(d)].name()),
String(reflect[Dict[String, Int]].name()),
)
assert_equal(d["b"], 2)
def test_array() raises:
# make: an unannotated bracket literal is an Array
var lit = [1, 2, 3]
assert_equal(lit[2], 3)
assert_equal(
String(reflect[type_of(lit)].name()),
String(reflect[Array[Int, 3]].name()),
)
assert_equal(Array[Int, 3](fill=7)[2], 7)
var squares = Array[Int, 4](fill_with=lambda (i: Int) -> Int: i * i)
assert_equal(squares[3], 9)
assert_equal(Array[Int, 2]()[1], 0) # default values
var raw = Array[Int, 2](uninitialized=True)
raw[0] = 5
raw[1] = 6
assert_equal(raw[0] + raw[1], 11)
# convert
var a: Array[Int32, 4] = [10, 20, 30, 40]
assert_equal(len(List(a)), 4) # growable copy
assert_equal(len(Span(a)), 4) # view
var joined = [1, 2].concat([3, 4, 5]) # moves both in
assert_equal(len(joined), 5)
var b = a.copy() # explicit copy, independent storage
b[0] = 99
assert_equal(a[0], 10)
# access: inline, contiguous storage like a C array
assert_equal(size_of[Array[Int32, 4]](), 4 * size_of[Int32]())
var p = a.unsafe_ptr()
assert_equal(p.unsafe_offset(3)[], a[3])
assert_equal(Int(p.unsafe_offset(1)) - Int(p), size_of[Int32]())
# a type-erased pointer reaches C as void *: memset(void*, int, size_t)
var buf = Array[UInt8, 8](fill=7)
_ = external_call["memset", OpaquePointer[MutAnyOrigin]](
buf.unsafe_ptr().unsafe_bitcast[NoneType](), Int32(0), 8
)
assert_equal(buf[7], 0)
def test_array_list_moves() raises:
var l: List[Int] = [7, 8, 9]
var from_list = Array[Int, 3](
fill_with=lambda (i: Int) {imm l} -> Int: l[i]
)
assert_equal(from_list[2], 9) # List -> Array; you pick n
assert_equal(len(Span(l)), 3) # view a List, no copy
assert_equal(len(Span(from_list)), 3) # view an Array, no copy
def test_simd_array_list() raises:
# List -> Array: view the buffer as an Array, then copy it out
var src: List[Int] = [1, 2, 3, 4]
var viewed = src.unsafe_ptr().unsafe_bitcast[Array[Int, 4]]()[].copy()
assert_equal(viewed[3], 4)
var names: List[String] = ["a", "b"] # non-numeric Copyable T
var named = names.unsafe_ptr().unsafe_bitcast[Array[String, 2]]()[].copy()
assert_equal(named[1], "b")
# N comes from the Array's type, known at compile time
comptime N = type_of(viewed).length
assert_equal(N, 4)
assert_equal(src.unsafe_ptr().unsafe_load[width=N]()[2], 3)
var v = SIMD[DType.float32, 4](1, 2, 3, 4)
var a = Array[Float32, 4](uninitialized=True)
a.unsafe_ptr().unsafe_store(v) # SIMD -> Array: one vector store
assert_equal(a[3], 4.0)
var back = a.unsafe_ptr().unsafe_load[width=4]() # Array -> SIMD
assert_true(back == v)
var l = List(a)
var lv = l.unsafe_ptr().unsafe_load[width=4]() # List -> SIMD
assert_true(lv == v)
l.unsafe_ptr().unsafe_store(lv * 10) # SIMD -> List
assert_equal(l[1], 20.0)
var lanes = Array[Float32, 4](
fill_with=lambda (i: Int) {imm v} -> Float32: v[i]
)
assert_equal(lanes[0], 1.0) # lane by lane
def test_list() raises:
var lst: List[Int] = [1, 2, 3]
assert_equal(len(lst), 3)
assert_equal(lst[0], 1) # one element, by reference
var view: Span[Int, _] = lst[0:2] # a Span view, no copy
assert_equal(len(view), 2)
var filled = List[Int](length=4, fill=0)
assert_equal(len(filled), 4)
assert_equal(filled[2], 0)
var r = List(range(5)) # range -> List
assert_equal(len(r), 5)
assert_equal(r[4], 4)
var roomy = List[Int](capacity=8) # empty, with room for 8
assert_equal(len(roomy), 0)
assert_true(roomy.capacity() >= 8)
var copied = List(lst) # from any iterable
assert_equal(len(copied), 3)
var alloc = lst.unsafe_take_allocation() # the buffer moves out
var left = len(lst)
dealloc(alloc^) # free before any assert can raise
assert_equal(left, 0)
def test_dict() raises:
var d = Dict[Int, String]()
d[1] = "one" # fill with d[k] = v
d[2] = "two"
assert_equal(d.setdefault(3, "three"), "three") # insert-if-absent
assert_true(d.get(1)) # Optional[V]
assert_false(d.get(99))
assert_true(1 in d)
assert_equal(d.pop(2), "two") # value, removes it
with assert_raises():
_ = d.pop(2) # already removed
assert_equal(len(List(d.values())), 2) # materialize the iterator
ref slot = d.setdefault(4, "four") # a ref into the Dict
slot = "FOUR"
assert_equal(d[4], "FOUR")
assert_equal(d.find(1).value(), "one") # find is Optional[V] too
assert_equal(d.get(1, "none"), "one") # value, or default
assert_equal(d.get(99, "none"), "none")
var keyed = Dict[String, Int].fromkeys(["a", "b"], 0) # every key -> 0
assert_equal(len(keyed), 2)
assert_equal(keyed["b"], 0)
def test_optional() raises:
var o = Optional(5) # from a value
assert_true(Bool(o))
assert_equal(o.value(), 5) # ref
assert_equal(o[], 5) # ref via []
var empty = Optional[Int](None) # empty
assert_false(Bool(empty))
var empty2 = Optional[Int]() # empty, explicit
assert_false(Bool(empty2))
assert_equal(empty.or_else(99), 99) # value, or default
var seven = Optional(7)
assert_equal(seven.take(), 7) # move value out
with assert_raises():
_ = empty[] # [] raises on empty; value() and take() abort
def main() raises:
test_establishing_types()
test_casting()
test_numbers()
test_numeric_creation()
test_numeric_conversion()
test_simd()
test_string()
test_parse_failures()
test_utf8()
test_pointers()
test_collection_literals()
test_array()
test_array_list_moves()
test_simd_array_list()
test_list()
test_dict()
test_optional()
@@ -0,0 +1,207 @@
# ===----------------------------------------------------------------------=== #
# 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 for the Mojo Ownership cheat sheet.
#
# Each test asserts a behavioral claim the card makes, so the card fails CI if a
# claim drifts. The compile-error boundaries the card states (used-after-transfer,
# `mut` needs a mutable arg, `var x = plain_copyable` errors) cannot be asserted
# at runtime and are not covered here.
# ===----------------------------------------------------------------------=== #
from std.testing import assert_equal
struct Box(ImplicitlyCopyable, Movable):
var v: Int
def __init__(out self, v: Int):
self.v = v
def take_imm(imm x: Int) -> Int: # imm = immutable borrow
return x
def take_mut(mut x: Int): # mut = mutable borrow (writes through)
x += 100
def take_var(var b: Box) -> Int: # var = owns the value
return b.v
def first[T: Movable](ref xs: List[T]) -> ref[xs[0]] T:
return xs[0] # len(xs) known to be > 0
# Literals / Trivial values: a fixed-width scalar is a one-lane SIMD.
# var owns; ref refers and writes through.
def test_var_owns_ref_refers() raises:
var data: List[Int] = [1, 2, 3]
ref view = data[0]
view = 9
assert_equal(data[0], 9)
# Var assignment: construct / implicit copy / explicit copy / transfer / copy-out-of-ref.
def test_var_assignment() raises:
var made = Box(1) # construct
assert_equal(made.v, 1)
var icopy = made # implicit copy (ImplicitlyCopyable)
assert_equal(icopy.v, 1)
assert_equal(made.v, 1) # a copy leaves the source owning its value
var ecopy = made.copy() # explicit copy
assert_equal(ecopy.v, 1)
var lst: List[Box] = [Box(7)]
ref r = lst[0]
var copied = r # copy out of a reference
assert_equal(copied.v, 7)
var transferred = made^ # transfer (last use of made)
assert_equal(transferred.v, 1)
# Mutability: mut writes through; imm borrows.
def test_mut_and_read() raises:
var m = 0
take_mut(m)
assert_equal(m, 100)
assert_equal(take_imm(m), 100)
# Call sites into an owning var param follow the var assignment rules.
def test_call_sites() raises:
assert_equal(take_var(Box(1)), 1) # construct into the arg
var b = Box(2)
assert_equal(take_var(b), 2) # f(x): implicit copy; b still usable
assert_equal(b.v, 2)
assert_equal(take_var(b.copy()), 2) # f(x.copy()): explicit copy
var lst: List[Box] = [Box(3)]
ref r = lst[0]
assert_equal(take_var(r), 3) # a reference copies out
assert_equal(take_var(b^), 2) # f(x^): transfer (last use of b)
# Origins: a ref return writes through to its source.
def test_ref_return_origin() raises:
var lst: List[Int] = [10, 20, 30]
ref x = first(lst)
x = 99
assert_equal(lst[0], 99)
# Returns: implicit copy / explicit copy / transfer out.
def ret_copy() -> Box:
var b = Box(5)
return b
def ret_explicit() -> Box:
var b = Box(6)
return b.copy()
def ret_transfer() -> Box:
var b = Box(7)
return b^
def test_returns() raises:
assert_equal(ret_copy().v, 5)
assert_equal(ret_explicit().v, 6)
assert_equal(ret_transfer().v, 7)
# Non-owning views: a contiguous slice is a Span view that writes through to the
# source (no copy); a codepoint slice is a StringSpan view.
def test_views() raises:
var data: List[String] = ["a", "b", "c", "d", "e"]
var s = data[1:3] # contiguous slice returns a Span view, no copy
s[0] = "X" # writes through to the source
assert_equal(data[1], "X")
assert_equal(s[0], "X")
var text = "Hello, World!"
var hi = text[codepoint=0:5] # StringSpan view
assert_equal(String(hi), "Hello")
# Consuming iteration: `^` drains a collection, moving each element out.
def test_consuming_iteration() raises:
var items: List[Box] = [Box(1), Box(2), Box(3)]
var total = 0
for var x in items^: # items drained; each x is owned
total += x.v
assert_equal(total, 6)
# --- opting out: pinned and linear types ---
struct Handle(not Movable):
var fd: Int
def __init__(out self, fd: Int):
self.fd = fd
struct Lease(not Deinitable else "call 'release()' to return the lease"):
var id: Int
def __init__(out self, id: Int):
self.id = id
def release(deinit self) -> Int: # the only way to end a Lease
return self.id
def test_opt_outs() raises:
var h = Handle(3) # pinned in place, still usable
assert_equal(h.fd, 3)
var lease = Lease(7)
assert_equal(lease^.release(), 7)
# --- captures use the argument conventions ---
def test_captures() raises:
var n = 10
var s = String("hi")
var t = String("moved")
def peek() {imm n} -> Int:
return n
def bump() {mut n}:
n += 1
def keep() {var s} -> String:
s += "!"
return s
def take() {var t^} -> String:
return t
bump()
assert_equal(n, 11) # mut writes back
assert_equal(peek(), 11)
assert_equal(keep(), "hi!") # var owns a copy
assert_equal(s, "hi") # the original is untouched
assert_equal(take(), "moved") # var ...^ owns the original
def main() raises:
test_var_owns_ref_refers()
test_var_assignment()
test_mut_and_read()
test_call_sites()
test_ref_return_origin()
test_returns()
test_views()
test_consuming_iteration()
test_opt_outs()
test_captures()
@@ -0,0 +1,259 @@
# ===----------------------------------------------------------------------=== #
# 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_traits.mojo
# Tests for the Mojo "traits" cheat-sheet card.
#
# Trait conformance is a compile-time fact, so most of this file is a
# COMPILE-FLOOR: if a claimed conformance or required-method set stops being
# true, this file stops compiling. A handful of behaviors are also asserted at
# runtime.
#
# Not tested (no portable runtime API to assert):
# - Hasher internals; Strategy (property-based, needs an Rng)
# - the rendered text of an else message (it appears only in a compile
# error)
# - var b = a^, return local^, and append() rejecting a non-Movable value
# (compile errors)
# - Identifiable __is__ (no portable value-type identity to assert)
# - PathLike / ConvertibleToPython / ConvertibleFromPython (need os / Python)
# - exact signature text of each requirement (the compile-floor covers that a
# conforming type satisfies the trait, not the literal spelling)
from std.testing import assert_equal, assert_false, assert_true
from std.math import ceil, floor, trunc
# A struct that conforms to the value + compare + format traits the card lists.
# Implementing only the required methods (__eq__, __lt__, write_to) and letting
# the rest be provided/synthesized is itself the test: it compiles only if the
# card's required-method claims are correct.
struct Meters(Comparable, Copyable, Movable, Writable):
var v: Int
def __init__(out self, v: Int):
self.v = v
def __eq__(self, other: Self) -> Bool:
return self.v == other.v
def __lt__(self, rhs: Self) -> Bool:
return self.v < rhs.v
def write_to(self, mut writer: Some[Writer]):
writer.write(self.v, "m")
def test_value_compare_format_floor() raises:
# Copyable / Movable: build and store in a List
var xs: List[Meters] = [Meters(3), Meters(1), Meters(2)]
assert_equal(len(xs), 3)
# Comparable: __lt__ implemented; __gt__/__le__/__ge__ provided
assert_true(Meters(1) < Meters(2))
assert_true(Meters(2) > Meters(1))
assert_true(Meters(2) <= Meters(2))
# Equatable (refined by Comparable): __eq__ implemented, __ne__ provided
assert_true(Meters(1) == Meters(1))
assert_true(Meters(1) != Meters(2))
# Writable: String() calls write_to()
assert_equal(String(Meters(5)), "5m")
@fieldwise_init
struct Seven(Floatable, Intable): # conforms by implementing the methods
var v: Int
def __int__(self) -> Int:
return self.v
def __float__(self) -> Float64:
return Float64(self.v)
def test_conversions() raises:
# Boolable / Intable / Floatable on builtins
assert_true(Bool(1))
assert_equal(Int(Float64(3.9)), 3) # Float64->Int truncates toward zero
assert_equal(Float64(5), 5.0) # Int -> Float64
# Intable converts to any integer type; Floatable only to Float64
var s = Seven(7)
assert_equal(Int8(s), 7)
assert_equal(UInt64(s), 7)
assert_equal(Int128(s), 7)
assert_equal(Float64(s), 7.0)
def test_sized() raises:
assert_equal(len([1, 2, 3]), 3)
assert_equal(len(["a", "b"]), 2)
def test_unary_math() raises:
# Absable / Powable / Roundable
assert_equal(abs(-5), 5)
assert_equal(2**8, 256)
assert_equal(round(3.6), 4.0)
# Ceilable / Floorable / Truncable
assert_equal(ceil(2.1), 3.0)
assert_equal(floor(2.9), 2.0)
assert_equal(trunc(2.9), 2.0)
def test_divmod() raises:
# DivModable -> divmod(); the tuple is (quotient, remainder)
var qr = divmod(7, 2)
assert_equal(qr[0], 3)
assert_equal(qr[1], 1)
def test_comparable_builtins() raises:
assert_true(1 < 2)
assert_true("a" < "b")
def test_hashable() raises:
# Hashable must agree with Equatable: equal values hash equal
assert_equal(hash(String("mojo")), hash(String("mojo")))
def test_iterable() raises:
# Iterable + Iterator drive the for loop
var total = 0
for x in [10, 20, 30]:
total += x
assert_equal(total, 60)
def test_conformance_claims() raises:
# The card's conformance claims, as a compile-time check.
assert_true(conforms_to(String, Writable))
assert_true(conforms_to(String, Equatable))
assert_true(conforms_to(String, Comparable))
assert_true(conforms_to(String, Hashable))
assert_true(conforms_to(Int, Intable))
assert_true(conforms_to(Int, Comparable))
# Refinement: Comparable refines Equatable, so an ordered type is equatable.
assert_true(conforms_to(Int, Equatable))
# Movable is needed to put a value into a container, not to name one.
struct Pinned(not Movable):
var x: Int
def __init__(out self, x: Int):
self.x = x
def unpin(deinit self) -> Int:
return self.x
def take_pinned(var p: Pinned) -> Int:
return p.x
struct Linear(not Deinitable):
var x: Int
def __init__(out self, x: Int):
self.x = x
def done(deinit self) -> Int: # the only way to end a Linear value
return self.x
def make_pinned() -> Pinned:
return Pinned(7) # a fresh value returns without a move
struct Undeclared: # no conformance list at all
var x: Int
def __init__(out self, x: Int):
self.x = x
def test_movable_opt_outs() raises:
# Movable (and Deinitable) are implicit; Copyable is not
assert_true(conforms_to(Undeclared, AnyType))
assert_true(conforms_to(Undeclared, Movable))
assert_true(conforms_to(Undeclared, Deinitable))
assert_false(conforms_to(Undeclared, Copyable))
var moved = Undeclared(1)
var target = moved^ # relocates to a new binding
assert_equal(target.x, 1)
var pins = List[Pinned]() # a non-movable type can name a List
assert_equal(len(pins), 0)
var maybe = Optional[Pinned]() # ...or an empty Optional
assert_true(not maybe)
var p = make_pinned()
assert_equal(p.x, 7)
# ^ transfers without Movable when the value is consumed where it is
var into_arg = Pinned(8)
assert_equal(take_pinned(into_arg^), 8) # into a var argument
var into_deinit = Pinned(9)
assert_equal(into_deinit^.unpin(), 9) # into a deinit method
var l = Linear(3)
assert_equal(l^.done(), 3)
# Conformance syntax: a conditional conformance exists only when proven.
@fieldwise_init
struct Box[T: Copyable & Deinitable](Hashable where conforms_to(T, Hashable)):
var value: Self.T
struct NoHash(Copyable):
var x: Int
def __init__(out self, x: Int):
self.x = x
def test_conformance_syntax() raises:
assert_true(conforms_to(Box[Int], Hashable)) # T is Hashable, so Box is
assert_false(conforms_to(Box[NoHash], Hashable)) # T isn't, so Box isn't
assert_equal(hash(Box[Int](5)), hash(Box[Int](5)))
var plain = Box[NoHash](NoHash(1)) # still a Box, just not Hashable
assert_equal(plain.value.x, 1)
def test_string_not_sized() raises:
var s = String("café")
assert_equal(s.byte_length(), 5)
assert_equal(s.count_codepoints(), 4)
assert_equal(s.count_graphemes(), 4)
# Diagnostics: messages after else compile as literals.
def chunk[
w: Int
]() -> Int where w.is_power_of_two() else ("'w' must be a power of two"):
return w
def test_else_messages() raises:
assert_equal(chunk[8](), 8) # a passing condition shows no message
def main() raises:
test_value_compare_format_floor()
test_conversions()
test_sized()
test_unary_math()
test_divmod()
test_comparable_builtins()
test_hashable()
test_iterable()
test_conformance_claims()
test_movable_opt_outs()
test_conformance_syntax()
test_else_messages()
test_string_not_sized()
@@ -0,0 +1,255 @@
# ===----------------------------------------------------------------------=== #
# 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_types_and_literals.mojo
# Tests for the Mojo "Types & Literals" cheat-sheet card.
#
# Not tested (compile-error claims or no portable runtime API to assert):
# - "no implicit numeric conversion" is a compile error, not runtime
# - \u and \U reject surrogate code points (U+D800 to U+DFFF) at compile time
# - a float literal never becomes an integer type (compile error)
# - len(s) on a string and t-string format specifiers are compile errors
# - Int128 / Int256 are software-emulated (no observable runtime difference)
# - a shift at or above the bit width has no defined result
from std.collections import Set
from std.math import cos, fma, inf, nan, sin, sqrt
from std.testing import assert_equal, assert_false, assert_true
from std.sys.info import bit_width_of
def test_simd_is_the_foundation() raises:
var v = SIMD[.float32, 4](1.0, 2.0, 3.0, 4.0)
var d = v * 2.0
assert_equal(d[1], 4.0) # every lane scaled
v[0] = 5.0 # write one lane
assert_equal(v.reduce_add(), 14.0) # 5 + 2 + 3 + 4
def test_conversions_explicit() raises:
var i = 42
assert_equal(Float64(i), 42.0)
var g = Float64(i).cast[.int32]() # between SIMD types
assert_equal(g, Int32(42))
def test_integer_overflow_wraps() raises:
# signed overflow wraps (two's complement)
assert_equal(Int8(127) + 1, Int8(-128))
def test_float_to_int_truncates() raises:
# truncates toward zero
assert_equal(Int(Float64(3.9)), 3)
def test_bounds() raises:
assert_equal(UInt8.MAX, UInt8(255))
assert_equal(Int8.MIN, Int8(-128))
assert_equal(Float32.MAX, inf[DType.float32]()) # MAX is inf for floats
assert_true(Float32.MAX_FINITE < Float32.MAX)
var n = nan[DType.float64]()
assert_false(n == n) # nan never equals itself
def test_contextual_dtype() raises:
var a = SIMD[.float32, 4](1, 2, 3, 4) # DType inferred from context
var b = SIMD[DType.float32, 4](1, 2, 3, 4)
assert_true(a == b)
def test_literals_wrap_silently() raises:
var b: Int8 = 300
var u: UInt8 = -1
assert_equal(b, 44)
assert_equal(u, 255)
def test_bit_width() raises:
# bit_width_of[Int]() from std.sys.info; 64 on this platform
assert_equal(bit_width_of[Int](), 64)
def test_number_literals() raises:
assert_equal(0xFF, 255)
assert_equal(0o52, 42)
assert_equal(0b1010, 10)
assert_equal(1_000_000, 1000000)
def test_triple_quote_keeps_layout() raises:
# newlines AND indentation are part of the string
var s = """line one
line two"""
assert_equal(s, "line one\n line two")
def test_adjacent_literals_join() raises:
var same_line = "abcd"
assert_equal(same_line, "abcd")
var across_lines = "Content of line 1. Content of line 2."
assert_equal(across_lines, "Content of line 1. Content of line 2.")
def test_unicode_escapes() raises:
assert_equal("\u20AC", "€") # lowercase \u, 4 digits (EURO)
assert_equal("\U0001F44B", "👋") # uppercase \U, 8 digits (above U+FFFF)
def test_tstring_interpolates() raises:
var who = "Mojo"
assert_equal(String(t"x = {who}"), "x = Mojo")
assert_equal(String(t"sum = {1 + 2}"), "sum = 3")
def test_raw_tstring() raises:
var who = "Mojo"
# raw: backslash stays literal, interpolation still happens
assert_equal(String(rt"raw\path {who}"), "raw\\path Mojo")
def test_collection_literals() raises:
# A bracket literal infers a fixed-size Array; annotating gets a List, and
# only the List grows.
var fixed = [1, 2, 3]
assert_equal(len(fixed), 3)
var nums: List[Int] = [1, 2, 3]
nums.append(4)
assert_equal(len(nums), 4)
var d = {"id": 1, "qty": 9}
assert_equal(d["qty"], 9)
var s = {1, 2, 3} # Set
assert_equal(len(s), 3)
assert_true(2 in s)
var pair = (1, "a", 2.0)
assert_equal(pair[0], 1)
def test_string_length() raises:
var s = "héllo"
assert_equal(s.byte_length(), 6) # UTF-8 bytes
assert_equal(len(s.codepoints()), 5) # Unicode code points
assert_equal(len(s.graphemes()), 5) # user-visible characters
def test_worth_knowing() raises:
# fmt: off
assert_equal('A', "A") # no character type: single quotes make a string
# fmt: on
assert_equal(ord("A"), 65)
assert_equal(chr(66), "B")
var a = -7
assert_equal(a / 2, -3) # / truncates toward zero
assert_equal(a // 2, -4) # // floors
assert_equal(7 / 2, 3.5) # the literal expression stays exact
var f: Float64 = -7.0
assert_equal(f / 2, -3.5) # / on floats is true division
assert_equal(f // 2, -4.0) # // floors for floats too
def test_scalar_aliases_cast() raises:
var float: Float64 = 42.0
var float32 = float.cast[.float32]() # cast works on named aliases
var scalar = Scalar[.float64](float)
var scalar16 = scalar.cast[.float16]()
assert_equal(float32, Float32(42.0))
assert_equal(scalar16, Float16(42.0))
def test_simd_construction() raises:
var broadcast = SIMD[DType.float64, 2](42.0) # broadcast all lanes
var specific = SIMD[DType.float64, 2](1.0, 2.0)
var zeros = SIMD[DType.float64, 2]() # zero-initialized
assert_equal(broadcast[1], 42.0)
assert_equal(specific[1], 2.0)
assert_equal(zeros.reduce_add(), 0.0)
def test_element_operations() raises:
var v = SIMD[DType.int32, 2](6, 3)
assert_true((v % 4) == SIMD[DType.int32, 2](2, 3))
assert_true((v // 2) == SIMD[DType.int32, 2](3, 1))
assert_true((v ^ 1) == SIMD[DType.int32, 2](7, 2)) # ^ is xor here
assert_true((~v) == SIMD[DType.int32, 2](-7, -4))
assert_true((v << 1) == SIMD[DType.int32, 2](12, 6))
var f = SIMD[DType.float32, 2](1, 4)
assert_true(sqrt(f) == SIMD[DType.float32, 2](1, 2))
assert_true(fma(f, f, f) == SIMD[DType.float32, 2](2, 20))
assert_true(sin(Float32(0)) == 0 and cos(Float32(0)) == 1)
def test_vector_operations() raises:
var v = SIMD[DType.int32, 4](1, 2, 3, 4)
assert_equal(v.reduce_mul(), 24)
assert_equal(v.reduce_min(), 1)
assert_equal(v.reduce_max(), 4)
assert_true(v.shuffle[3, 2, 1, 0]() == SIMD[DType.int32, 4](4, 3, 2, 1))
assert_true(v.slice[2]() == SIMD[DType.int32, 2](1, 2))
assert_equal(len(v.join(v)), 8)
var first, second = v.split()
# The halves' width stays the unevaluated `4 // 2`, so compare after a
# rebind. TODO(#101323): drop the rebind once split() halves unify with
# width 2.
assert_true(rebind[SIMD[.int32, 2]](first) == SIMD[.int32, 2](1, 2))
assert_true(rebind[SIMD[.int32, 2]](second) == SIMD[.int32, 2](3, 4))
def test_optionals() raises:
var foo: Optional[Int] = None
var bar: Optional[Int] = 42
assert_equal(foo.or_else(0), 0) # default fallback
assert_equal(bar.or_else(0), 42)
assert_false(Bool(foo)) # check then access
assert_true(Bool(bar))
assert_equal(bar.value(), 42)
def test_empty_collections() raises:
var list: List[Int] = []
var dict: Dict[String, Int] = {}
var set: Set[Int] = {} # naming Set needs the import
assert_equal(len(list), 0)
assert_equal(len(dict), 0)
assert_equal(len(set), 0)
def test_string_count_methods() raises:
var text = "café"
assert_equal(text.byte_length(), 5) # é is 2 bytes
assert_equal(text.count_codepoints(), 4)
assert_equal(text.count_graphemes(), 4)
def main() raises:
test_simd_is_the_foundation()
test_conversions_explicit()
test_integer_overflow_wraps()
test_float_to_int_truncates()
test_bounds()
test_contextual_dtype()
test_literals_wrap_silently()
test_bit_width()
test_number_literals()
test_triple_quote_keeps_layout()
test_adjacent_literals_join()
test_unicode_escapes()
test_tstring_interpolates()
test_raw_tstring()
test_collection_literals()
test_string_length()
test_worth_knowing()
test_scalar_aliases_cast()
test_simd_construction()
test_element_operations()
test_vector_operations()
test_optionals()
test_empty_collections()
test_string_count_methods()