Baseline: tree as shared

This commit is contained in:
alexm committed 2026-10-05 03:03:38 +00:00
commit 31f2fb8a5a
1679 files changed
+1024562

No files matched your search

@@ -0,0 +1,92 @@
# ===----------------------------------------------------------------------=== #
# 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_basics.mojo
# Tests for the Mojo "Basics" cheat-sheet card.
#
# 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
# - leading-zero decimals rejected: `0123` must error (use `0o` for octal)
from std.collections import Set
from std.testing import assert_equal
def risky() raises:
# mirrors the Errors panel: a function that may raise is marked `raises`
raise Error("boom")
def test_ref_writes_through() raises:
# `ref` binds a name to a value it doesn't own; writing through it updates
# the original.
var data: List[Int] = [1, 2, 3]
ref view = data[0]
view = 99
assert_equal(data[0], 99)
def test_literal_adapts() raises:
# a numeric literal adapts to the annotated type
var a: Float64 = 0.5
assert_equal(a, 0.5)
def test_set_literal_and_dedup() raises:
var primes = {1, 2, 3} # set display
assert_equal(len(primes), 3)
var bag = Set[Int]()
bag.add(4)
bag.add(4) # adding a duplicate is a no-op
assert_equal(len(bag), 1)
def test_power() raises:
assert_equal(2**10, 1024)
def test_errors_try_except() raises:
# Errors panel: raise / try / except e binds the error
var caught = String("")
try:
risky()
except e:
caught = String(e)
assert_equal(caught, "boom")
def test_conversions() raises:
# Built-in types note: cast explicitly, no implicit numeric conversion
var i = 42
assert_equal(Float64(i), 42.0)
assert_equal(Int(Float64(2.9)), 2) # truncates toward zero
assert_equal(String(i), "42")
def test_list_ops() raises:
# Lists panel
var xs: List[Int] = [1, 2, 3]
xs.append(4)
assert_equal(xs[0], 1)
assert_equal(len(xs), 4)
def main() raises:
test_ref_writes_through()
test_literal_adapts()
test_set_literal_and_dedup()
test_power()
test_errors_try_except()
test_conversions()
test_list_ops()
@@ -0,0 +1,196 @@
# ===----------------------------------------------------------------------=== #
# 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, trait bounds, running a function at
# compile time, comptime if/for, sys.info queries, comptime members, and the
# inlining decorators.
#
# 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.
# - numeric precision: float equality is touchy to assert, and 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.
# - 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
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():
return w # only callable when w is a power of two
def test_where() raises:
assert_equal(block[8](), 8)
# --- conformances: a trait bound admits only proven operations ---
def largest[T: Comparable & Copyable](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)
# --- 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 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 compiles ---
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 ---
@always_inline
def add_inline(a: Int, b: Int) -> Int:
return a + b
@no_inline
def add_separate(a: Int, b: Int) -> Int:
return a + b
def test_inlining() raises:
assert_equal(add_inline(2, 3), 5)
assert_equal(add_separate(2, 3), 5)
# --- 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_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,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.
# ===----------------------------------------------------------------------=== #
# 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):
# - parse FAILURES abort/raise paths beyond one sample (Int("3.5") raises)
# - .value()/.take() on an empty Optional abort (can't assert an abort)
# - @implicit conversions (a compile-time behavior, not a runtime value)
# - Python conversions (need the Python runtime); Float8 (needs a GPU)
from std.testing import assert_equal, assert_true, assert_false
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_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 an iterator over the bytes
assert_equal(len(String("abc").as_bytes()), 3)
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
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)
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
assert_equal(len(List(d.values())), 2) # materialize the iterator
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
def main() raises:
test_numbers()
test_simd()
test_string()
test_pointers()
test_list()
test_dict()
test_optional()
@@ -0,0 +1,162 @@
# ===----------------------------------------------------------------------=== #
# 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.
def test_int_simd_aliases() raises:
var i32: Int32 = 5
var s: SIMD[
DType.int32, 1
] = i32 # no conversion: Int32 IS SIMD[DType.int32, 1]
assert_equal(Int(s), 5)
# 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 moved = made^ # transfer (last use of made)
assert_equal(moved.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)
def main() raises:
test_int_simd_aliases()
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()
@@ -0,0 +1,136 @@
# ===----------------------------------------------------------------------=== #
# 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 (need a GPU, or no portable runtime API to assert):
# - DevicePassable / DeviceTypeEncoder (accelerator-only)
# - Hasher internals; Strategy (property-based, needs an Rng)
# - 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_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")
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
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))
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()
@@ -0,0 +1,125 @@
# ===----------------------------------------------------------------------=== #
# 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
# - nan == nan is False (nan construction left out to keep this portable)
# - Float8 needs a GPU; Int128 / Int256 are software-emulated
from std.testing import assert_equal
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))
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 pair = (1, "a", 2.0)
assert_equal(pair[0], 1)
def main() raises:
test_simd_is_the_foundation()
test_conversions_explicit()
test_integer_overflow_wraps()
test_float_to_int_truncates()
test_bounds()
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()