Baseline: tree as shared
This commit is contained in:
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()
|
||||
@@ -0,0 +1,428 @@
|
||||
# ===----------------------------------------------------------------------=== #
|
||||
# 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_closure_declarations.mojo
|
||||
# Tests for closure-declarations.mdx code examples.
|
||||
#
|
||||
# Skip (compile-error demonstrations and timing-only side effects):
|
||||
# - "Could not infer capture convention" diagnostic for `{}` and
|
||||
# omitted capture list referencing outer values.
|
||||
# - "'^' requires 'var' convention" for `{mut x^}`, `{imm x^}`,
|
||||
# `{ref x^}`.
|
||||
# - "default capture convention was already specified" for
|
||||
# `{mut, imm}`.
|
||||
# - "must be mutable for in-place operator destination" for
|
||||
# writing to an `imm`-captured name (bare-name default case).
|
||||
# - "register passible value can not be captured by 'mut'" for
|
||||
# `{mut name}` on an immutable register-passable arg.
|
||||
# - "cannot capture <name> by copy or move because it is not
|
||||
# register passable" for a non-register-passable `var` capture
|
||||
# inside a closure.
|
||||
# - "use of uninitialized value '<name>'" after `{var name^}`.
|
||||
# - `{var^}` copy-ctor timing assertion (the [copied] print at
|
||||
# closure-value assignment, not at declaration). Verified
|
||||
# empirically; cannot be asserted without redirecting stdout.
|
||||
from std.testing import assert_equal, assert_true
|
||||
|
||||
|
||||
# --- Intro example: imm capture ---
|
||||
|
||||
|
||||
def test_imm_intro() raises:
|
||||
var multiplier = 3
|
||||
|
||||
def scale(x: Int) {imm multiplier} -> Int:
|
||||
return x * multiplier
|
||||
|
||||
assert_equal(scale(5), 15)
|
||||
|
||||
|
||||
# --- imm: live updates ---
|
||||
|
||||
|
||||
def test_imm_live_updates() raises:
|
||||
var limit = 10
|
||||
|
||||
def check(x: Int) {imm limit} -> Bool:
|
||||
return x < limit
|
||||
|
||||
assert_equal(check(5), True)
|
||||
limit = 3
|
||||
assert_equal(check(5), False)
|
||||
|
||||
|
||||
# --- imm: implicit form ---
|
||||
|
||||
|
||||
def test_imm_implicit() raises:
|
||||
var a = 1
|
||||
var b = 2
|
||||
|
||||
def sum_ab() {imm} -> Int:
|
||||
return a + b
|
||||
|
||||
assert_equal(sum_ab(), 3)
|
||||
|
||||
|
||||
# --- bare name defaults to imm ---
|
||||
|
||||
|
||||
def test_bare_name_default_imm() raises:
|
||||
var x = 10
|
||||
|
||||
def show() {x} -> Int:
|
||||
return x
|
||||
|
||||
assert_equal(show(), 10)
|
||||
|
||||
|
||||
# --- mut: explicit form ---
|
||||
|
||||
|
||||
def test_mut_explicit() raises:
|
||||
var total = 0
|
||||
|
||||
def accumulate(value: Int) {mut total}:
|
||||
total += value
|
||||
|
||||
accumulate(10)
|
||||
accumulate(20)
|
||||
assert_equal(total, 30)
|
||||
|
||||
|
||||
# --- mut: implicit form ---
|
||||
|
||||
|
||||
def test_mut_implicit() raises:
|
||||
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")
|
||||
|
||||
|
||||
# --- var: explicit form, snapshot at declaration ---
|
||||
|
||||
|
||||
def test_var_explicit_snapshot() raises:
|
||||
var snapshot = 42
|
||||
|
||||
def frozen() {var snapshot} -> Int:
|
||||
return snapshot
|
||||
|
||||
snapshot = 999
|
||||
assert_equal(frozen(), 42)
|
||||
assert_equal(snapshot, 999) # outer survives
|
||||
|
||||
|
||||
# --- var: implicit form ---
|
||||
|
||||
|
||||
def test_var_implicit() raises:
|
||||
var x = 10
|
||||
var y = 20
|
||||
|
||||
def snap() {var} -> Int:
|
||||
return x + y
|
||||
|
||||
x = 0
|
||||
y = 0
|
||||
assert_equal(snap(), 30)
|
||||
_ = x
|
||||
_ = y
|
||||
|
||||
|
||||
# --- var name^: move capture ---
|
||||
|
||||
|
||||
def test_var_move_capture() raises:
|
||||
var data: List[Int] = [1, 2, 3]
|
||||
|
||||
def take_data() {var data^} -> Int:
|
||||
return len(data)
|
||||
|
||||
assert_equal(take_data(), 3)
|
||||
# data is consumed; referencing it here would be a compile error
|
||||
|
||||
|
||||
# --- bare name^: move capture (equivalent to var name^) ---
|
||||
|
||||
|
||||
def test_bare_move_capture() raises:
|
||||
var data: List[Int] = [1, 2, 3]
|
||||
|
||||
def take_data() {data^} -> Int:
|
||||
return len(data)
|
||||
|
||||
assert_equal(take_data(), 3)
|
||||
# data is consumed; referencing it here would be a compile error
|
||||
|
||||
|
||||
# --- var^: closure value is Copyable ---
|
||||
|
||||
|
||||
def test_var_caret_copyable_closure() raises:
|
||||
var label = "sensor-1"
|
||||
|
||||
def tag() {var^} -> String:
|
||||
return label
|
||||
|
||||
var clone = tag
|
||||
assert_equal(tag(), "sensor-1")
|
||||
assert_equal(clone(), "sensor-1")
|
||||
|
||||
|
||||
# --- ref: parametric mutability ---
|
||||
#
|
||||
# Body refactored to return a Bool instead of printing, so the
|
||||
# closure's view of origin mutability is testable.
|
||||
|
||||
|
||||
def parametric_returns_mut(ref x: List[Int]) -> Bool:
|
||||
def borrow() {ref x} -> Bool:
|
||||
comptime if origin_of(x).mut:
|
||||
return True
|
||||
else:
|
||||
return False
|
||||
|
||||
return borrow()
|
||||
|
||||
|
||||
def call_with_immut(imm x: List[Int]) -> Bool:
|
||||
return parametric_returns_mut(x)
|
||||
|
||||
|
||||
def call_with_mut(mut x: List[Int]) -> Bool:
|
||||
return parametric_returns_mut(x)
|
||||
|
||||
|
||||
def test_ref_parametric_mutability() raises:
|
||||
var nums: List[Int] = [10, 20, 30]
|
||||
assert_equal(call_with_immut(nums), False)
|
||||
assert_equal(call_with_mut(nums), True)
|
||||
|
||||
|
||||
# --- Empty capture list `{}` ---
|
||||
|
||||
|
||||
def test_empty_capture_list() raises:
|
||||
def doubled(x: Int) {} -> Int:
|
||||
return x * 2
|
||||
|
||||
assert_equal(doubled(5), 10)
|
||||
|
||||
|
||||
# --- No capture list (equivalent to `{}`) ---
|
||||
|
||||
|
||||
def test_no_capture_list() raises:
|
||||
def doubled(x: Int) -> Int:
|
||||
return x * 2
|
||||
|
||||
assert_equal(doubled(6), 12)
|
||||
|
||||
|
||||
# --- Mixing conventions: per-entry independence ---
|
||||
|
||||
|
||||
def test_mixed_conventions() raises:
|
||||
var config: String = "prod"
|
||||
var count = 0
|
||||
var label: String = "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" # outer mutation
|
||||
# closure's `label` is the def-time snapshot
|
||||
assert_equal(process(), "prod:2:run-1")
|
||||
assert_equal(count, 2) # mut count flowed through
|
||||
_ = label
|
||||
|
||||
|
||||
# --- Default convention with explicit override ---
|
||||
|
||||
|
||||
def test_default_convention_override() raises:
|
||||
var a = 1
|
||||
var b = 2
|
||||
var z: String = "snapshot"
|
||||
|
||||
def mixed() {mut, var z} -> String:
|
||||
a += 10 # 'a' uses default: mut
|
||||
b += 20 # 'b' uses default: mut
|
||||
return String(a) + "," + String(b) + "," + z
|
||||
|
||||
assert_equal(mixed(), "11,22,snapshot")
|
||||
z = "changed"
|
||||
assert_equal(mixed(), "21,42,snapshot")
|
||||
assert_equal(a, 21)
|
||||
assert_equal(b, 42)
|
||||
_ = z
|
||||
|
||||
|
||||
# --- Order independence of default-convention entry ---
|
||||
|
||||
|
||||
def test_default_position_independent() raises:
|
||||
var x = 1
|
||||
var y = 100
|
||||
|
||||
# `mut` as default, with explicit `var y` override
|
||||
def first() {mut, var y} -> Int:
|
||||
x += 1
|
||||
return x + y
|
||||
|
||||
# Same list with positions reversed
|
||||
def second() {var y, mut} -> Int:
|
||||
x += 1
|
||||
return x + y
|
||||
|
||||
assert_equal(first(), 2 + 100) # x bumped to 2
|
||||
assert_equal(second(), 3 + 100) # x bumped to 3
|
||||
assert_equal(x, 3)
|
||||
|
||||
|
||||
# --- Parametric closure: simple type parameter ---
|
||||
|
||||
|
||||
def test_parametric_closure_basic() raises:
|
||||
def double[T: Intable](x: T) {} -> Int:
|
||||
return Int(x) * 2
|
||||
|
||||
assert_equal(double[Int](5), 10)
|
||||
assert_equal(double[Int](7), 14)
|
||||
|
||||
|
||||
# --- Parametric closure: captures outer value ---
|
||||
|
||||
|
||||
def test_parametric_closure_with_capture() raises:
|
||||
var factor = 4
|
||||
|
||||
def scale_to[T: Intable](x: T) {imm factor} -> Int:
|
||||
return Int(x) * factor
|
||||
|
||||
assert_equal(scale_to[Int](3), 12)
|
||||
factor = 10
|
||||
assert_equal(scale_to[Int](3), 30)
|
||||
|
||||
|
||||
# --- Effects: raises on closure ---
|
||||
|
||||
|
||||
def test_closure_raises() raises:
|
||||
var divisor = 2
|
||||
|
||||
def divide(x: Int) raises {var divisor} -> Int:
|
||||
if divisor == 0:
|
||||
raise Error("divide by zero")
|
||||
return x // divisor
|
||||
|
||||
assert_equal(divide(10), 5)
|
||||
|
||||
|
||||
def test_closure_raises_actually_raises() raises:
|
||||
var divisor = 0
|
||||
|
||||
def divide(x: Int) raises {var divisor} -> Int:
|
||||
if divisor == 0:
|
||||
raise Error("divide by zero")
|
||||
return x // divisor
|
||||
|
||||
var caught = False
|
||||
try:
|
||||
_ = divide(10)
|
||||
except e:
|
||||
caught = True
|
||||
assert_true(caught)
|
||||
|
||||
|
||||
# --- Device-passable closure behavior ---
|
||||
|
||||
|
||||
def test_closure_device_passable() raises:
|
||||
var base = 10
|
||||
|
||||
def shift(x: Int) {var base} -> Int:
|
||||
return x + base
|
||||
|
||||
assert_equal(shift(3), 13)
|
||||
assert_equal(shift(7), 17)
|
||||
|
||||
|
||||
# --- Nesting: closure inside a closure ---
|
||||
|
||||
|
||||
def test_nested_closures() raises:
|
||||
var y = 4
|
||||
|
||||
def outer_fn() {var y} -> Int:
|
||||
def inner_fn() {var y} -> Int:
|
||||
return y
|
||||
|
||||
return inner_fn() + y
|
||||
|
||||
assert_equal(outer_fn(), 8)
|
||||
|
||||
|
||||
# --- Nesting: inner closure captures outer closure by name ---
|
||||
|
||||
|
||||
def test_nested_capture_closure_value() raises:
|
||||
var n = 3
|
||||
|
||||
def add(x: Int) {var n} -> Int:
|
||||
return x + n
|
||||
|
||||
def twice(x: Int) {var add} -> Int:
|
||||
return add(add(x))
|
||||
|
||||
assert_equal(twice(5), 11) # 5 + 3 + 3
|
||||
assert_equal(twice(0), 6) # 0 + 3 + 3
|
||||
|
||||
|
||||
def main() raises:
|
||||
test_imm_intro()
|
||||
test_imm_live_updates()
|
||||
test_imm_implicit()
|
||||
test_bare_name_default_imm()
|
||||
test_mut_explicit()
|
||||
test_mut_implicit()
|
||||
test_var_explicit_snapshot()
|
||||
test_var_implicit()
|
||||
test_var_move_capture()
|
||||
test_bare_move_capture()
|
||||
test_var_caret_copyable_closure()
|
||||
test_ref_parametric_mutability()
|
||||
test_empty_capture_list()
|
||||
test_no_capture_list()
|
||||
test_mixed_conventions()
|
||||
test_default_convention_override()
|
||||
test_default_position_independent()
|
||||
test_parametric_closure_basic()
|
||||
test_parametric_closure_with_capture()
|
||||
test_closure_raises()
|
||||
test_closure_raises_actually_raises()
|
||||
test_closure_device_passable()
|
||||
test_nested_closures()
|
||||
test_nested_capture_closure_value()
|
||||
@@ -0,0 +1,352 @@
|
||||
# ===----------------------------------------------------------------------=== #
|
||||
# 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_compound_statements.mojo
|
||||
# Tests for compound-statements.mdx code examples.
|
||||
from std.sys import size_of
|
||||
from std.testing import assert_equal, assert_false, assert_true
|
||||
|
||||
|
||||
# --- If statements ---
|
||||
|
||||
|
||||
def test_if_elif_else_chain() raises:
|
||||
var result: String
|
||||
var x = 5
|
||||
if x > 0:
|
||||
result = "positive"
|
||||
elif x < 0:
|
||||
result = "negative"
|
||||
elif x == 0:
|
||||
result = "zero"
|
||||
else:
|
||||
result = "you should never get here"
|
||||
assert_equal(result, "positive")
|
||||
|
||||
x = -3
|
||||
if x > 0:
|
||||
result = "positive"
|
||||
elif x < 0:
|
||||
result = "negative"
|
||||
elif x == 0:
|
||||
result = "zero"
|
||||
assert_equal(result, "negative")
|
||||
|
||||
x = 0
|
||||
if x > 0:
|
||||
result = "positive"
|
||||
elif x < 0:
|
||||
result = "negative"
|
||||
elif x == 0:
|
||||
result = "zero"
|
||||
assert_equal(result, "zero")
|
||||
|
||||
|
||||
def test_single_line_if() raises:
|
||||
var result = String("placeholder")
|
||||
var x = 5
|
||||
if x > 0:
|
||||
result = "positive"
|
||||
assert_equal(result, "positive")
|
||||
|
||||
|
||||
# --- While loops ---
|
||||
|
||||
|
||||
def test_while_basic() raises:
|
||||
var count = 0
|
||||
var total = 0
|
||||
while count < 10:
|
||||
total += count
|
||||
count += 1
|
||||
assert_equal(count, 10)
|
||||
assert_equal(total, 45) # 0+1+...+9
|
||||
|
||||
|
||||
def test_while_break_continue() raises:
|
||||
# break exits the loop, continue skips to the next iteration.
|
||||
var processed = 0
|
||||
var i = 0
|
||||
while True:
|
||||
if i >= 10:
|
||||
break
|
||||
if i % 2 == 1:
|
||||
i += 1
|
||||
continue
|
||||
processed += 1
|
||||
i += 1
|
||||
assert_equal(processed, 5) # 0, 2, 4, 6, 8
|
||||
|
||||
|
||||
# --- For loops ---
|
||||
|
||||
|
||||
def test_for_conventions() raises:
|
||||
var list: List[String] = ["a", "b", "c", "d"]
|
||||
|
||||
for var item in list:
|
||||
item = item + "x" # works. item is mutable copy of list element
|
||||
# print(item) # prints "ax", then "bx", "cx", and "dx"
|
||||
assert_true(item.endswith("x"))
|
||||
assert_true(list == ["a", "b", "c", "d"]) # list is unchanged
|
||||
# print(list) # unchanged
|
||||
|
||||
for ref item in list:
|
||||
item = item + "x"
|
||||
# mutability picked up in reference to list element
|
||||
# print(item) # prints "ax", then "bx", "cx", and "dx"
|
||||
assert_true(item.endswith("x"))
|
||||
assert_true(list == ["ax", "bx", "cx", "dx"]) # list is changed
|
||||
# print(list) # changed to ["ax", "bx", "cx", "dx"]
|
||||
|
||||
|
||||
def test_for_range() raises:
|
||||
var total = 0
|
||||
for i in range(10):
|
||||
total += i
|
||||
assert_equal(total, 45)
|
||||
|
||||
|
||||
def test_for_destructuring() raises:
|
||||
# Tuple unpacking in the loop target.
|
||||
var pairs = [("a", 1), ("b", 2), ("c", 3)]
|
||||
var total = 0
|
||||
for _key, value in pairs:
|
||||
total += value
|
||||
assert_equal(total, 6)
|
||||
|
||||
|
||||
# --- For/while else clauses ---
|
||||
|
||||
|
||||
def test_for_else_no_break() raises:
|
||||
# else runs when the loop completes without break.
|
||||
var items = [1, 2, 3]
|
||||
var target = 99
|
||||
var found = False
|
||||
var ran_else = False
|
||||
for item in items:
|
||||
if item == target:
|
||||
found = True
|
||||
break
|
||||
else:
|
||||
ran_else = True
|
||||
assert_false(found)
|
||||
assert_true(ran_else)
|
||||
|
||||
|
||||
def test_for_else_with_break() raises:
|
||||
# else does NOT run when break exits the loop.
|
||||
var items = [1, 2, 3]
|
||||
var target = 2
|
||||
var found = False
|
||||
var ran_else = False
|
||||
for item in items:
|
||||
if item == target:
|
||||
found = True
|
||||
break
|
||||
else:
|
||||
ran_else = True
|
||||
assert_true(found)
|
||||
assert_false(ran_else)
|
||||
|
||||
|
||||
def test_while_else_no_break() raises:
|
||||
var i = 0
|
||||
var ran_else = False
|
||||
assert_false(ran_else) # sentinel: must transition to True via else
|
||||
while i < 5:
|
||||
i += 1
|
||||
else:
|
||||
ran_else = True
|
||||
assert_equal(i, 5)
|
||||
assert_true(ran_else)
|
||||
|
||||
|
||||
# --- Error handling ---
|
||||
|
||||
|
||||
def _risky() raises:
|
||||
raise Error("oops")
|
||||
|
||||
|
||||
def test_try_except_basic() raises:
|
||||
var caught = False
|
||||
try:
|
||||
_risky()
|
||||
except:
|
||||
caught = True
|
||||
assert_true(caught)
|
||||
|
||||
|
||||
def test_try_full_structure_no_error() raises:
|
||||
# try -> else -> finally when no error fires.
|
||||
var sequence = String("")
|
||||
try:
|
||||
sequence += "T"
|
||||
except _:
|
||||
sequence += "E"
|
||||
else:
|
||||
sequence += "L"
|
||||
finally:
|
||||
sequence += "F"
|
||||
assert_equal(sequence, "TLF")
|
||||
|
||||
|
||||
def test_try_full_structure_with_error() raises:
|
||||
# try -> except -> finally when an error fires.
|
||||
var sequence = String("")
|
||||
try:
|
||||
sequence += "T"
|
||||
_risky()
|
||||
except e:
|
||||
sequence += "E"
|
||||
else:
|
||||
sequence += "L"
|
||||
finally:
|
||||
sequence += "F"
|
||||
assert_equal(sequence, "TEF")
|
||||
|
||||
|
||||
def test_except_with_binding() raises:
|
||||
var msg = String("")
|
||||
try:
|
||||
_risky()
|
||||
except e:
|
||||
msg = String(e)
|
||||
assert_true("oops" in msg)
|
||||
|
||||
|
||||
def test_except_without_binding() raises:
|
||||
var caught = False
|
||||
try:
|
||||
_risky()
|
||||
except:
|
||||
caught = True
|
||||
assert_true(caught)
|
||||
|
||||
|
||||
# --- Typed errors ---
|
||||
|
||||
|
||||
@fieldwise_init
|
||||
struct NetworkError(ImplicitlyCopyable, Movable, Writable):
|
||||
var message: String
|
||||
var code: Int
|
||||
|
||||
def write_to[W: Writer](self, mut writer: W):
|
||||
writer.write("NetworkError(code=", self.code, "): ", self.message)
|
||||
|
||||
|
||||
def _fetch() raises NetworkError -> String:
|
||||
raise NetworkError("HTCPCP", 418)
|
||||
|
||||
|
||||
def test_typed_raises() raises:
|
||||
# raises Type infers the bound error's type and allows field access.
|
||||
var code = 0
|
||||
var msg = String("placeholder")
|
||||
try:
|
||||
_ = _fetch()
|
||||
except e:
|
||||
code = e.code
|
||||
msg = e.message
|
||||
assert_equal(code, 418)
|
||||
assert_equal(msg, "HTCPCP")
|
||||
|
||||
|
||||
# --- Context managers ---
|
||||
|
||||
|
||||
struct Scope(ImplicitlyCopyable):
|
||||
var label: String
|
||||
|
||||
def __init__(out self, label: String):
|
||||
self.label = label
|
||||
|
||||
def __enter__(self) -> Self:
|
||||
# perform setup tasks
|
||||
# print("entering", self.label) Not needed for testing
|
||||
return self
|
||||
|
||||
def __exit__(self):
|
||||
# perform cleanup tasks
|
||||
# print("exiting", self.label) Not needed for testing
|
||||
pass
|
||||
|
||||
|
||||
def test_custom_context_manager() raises:
|
||||
with Scope("setup") as s:
|
||||
assert_equal(s.label, "setup")
|
||||
|
||||
|
||||
# --- comptime if ---
|
||||
|
||||
|
||||
def test_comptime_if() raises:
|
||||
# Either branch may be selected depending on the target.
|
||||
var label: String
|
||||
comptime if size_of[Int]() == 8:
|
||||
label = "64-bit"
|
||||
else:
|
||||
label = "Probably 32-bit"
|
||||
assert_true(label == "64-bit" or label == "Probably 32-bit")
|
||||
|
||||
|
||||
# --- comptime for ---
|
||||
|
||||
|
||||
def test_comptime_for() raises:
|
||||
# The loop unrolls at compile time; body emits as total += 0; total += 1; ...
|
||||
var total = 0
|
||||
comptime for i in range(5):
|
||||
total += i
|
||||
assert_equal(total, 10) # 0+1+2+3+4
|
||||
|
||||
|
||||
# --- Closures with capture lists ---
|
||||
|
||||
|
||||
def test_closure_with_capture_list() raises:
|
||||
# {mut count} captures by mutable reference.
|
||||
var count = 0
|
||||
|
||||
def inner() {mut count}:
|
||||
count += 1
|
||||
|
||||
inner()
|
||||
inner()
|
||||
inner()
|
||||
assert_equal(count, 3)
|
||||
|
||||
|
||||
def main() raises:
|
||||
test_if_elif_else_chain()
|
||||
test_single_line_if()
|
||||
test_while_basic()
|
||||
test_while_break_continue()
|
||||
test_for_conventions()
|
||||
test_for_range()
|
||||
test_for_destructuring()
|
||||
test_for_else_no_break()
|
||||
test_for_else_with_break()
|
||||
test_while_else_no_break()
|
||||
test_try_except_basic()
|
||||
test_try_full_structure_no_error()
|
||||
test_try_full_structure_with_error()
|
||||
test_except_with_binding()
|
||||
test_except_without_binding()
|
||||
test_typed_raises()
|
||||
test_custom_context_manager()
|
||||
test_comptime_if()
|
||||
test_comptime_for()
|
||||
test_closure_with_capture_list()
|
||||
@@ -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.sys import align_of
|
||||
from std.testing import *
|
||||
|
||||
|
||||
@align(64)
|
||||
struct CacheAligned:
|
||||
var x: Int
|
||||
|
||||
|
||||
struct Container:
|
||||
var aligned: CacheAligned
|
||||
var other: Int
|
||||
|
||||
|
||||
def main() raises:
|
||||
# print(align_of[Container]()) # Prints 64
|
||||
assert_equal(align_of[Container](), 64, "align should be 64")
|
||||
@@ -0,0 +1,42 @@
|
||||
# ===----------------------------------------------------------------------=== #
|
||||
# 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 align_of, size_of
|
||||
from std.memory import alloc, dealloc
|
||||
from std.testing import *
|
||||
|
||||
|
||||
@align(64)
|
||||
struct CacheAligned:
|
||||
var data: Int # 8 bytes
|
||||
|
||||
|
||||
def demonstrate_array_stride() raises:
|
||||
var allocation = alloc[CacheAligned]({count = 4})
|
||||
var _ = allocation.unsafe_ptr() # `arr`
|
||||
|
||||
# print(align_of[CacheAligned]()) # 64
|
||||
# print(size_of[CacheAligned]()) # 64
|
||||
|
||||
var align = align_of[CacheAligned]()
|
||||
var size = size_of[CacheAligned]()
|
||||
|
||||
# All elements of arr are guaranteed to be 64-byte aligned
|
||||
|
||||
dealloc(allocation^)
|
||||
assert_equal(64, align, "align should be 64")
|
||||
assert_equal(64, size, "size_of should be 64")
|
||||
|
||||
|
||||
def main() raises:
|
||||
demonstrate_array_stride()
|
||||
@@ -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.
|
||||
# ===----------------------------------------------------------------------=== #
|
||||
|
||||
from std.sys import align_of
|
||||
from std.testing import *
|
||||
|
||||
|
||||
@align(64)
|
||||
struct CacheAligned:
|
||||
var data: Int
|
||||
|
||||
|
||||
def main() raises:
|
||||
# print(align_of[CacheAligned]()) # Prints 64
|
||||
assert_equal(align_of[CacheAligned](), 64, "align should be 64")
|
||||
@@ -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.
|
||||
# ===----------------------------------------------------------------------=== #
|
||||
|
||||
from std.sys import align_of
|
||||
from std.testing import *
|
||||
|
||||
|
||||
@fieldwise_init
|
||||
@align(128)
|
||||
struct Aligned[T: Copyable & Deinitable]:
|
||||
var value: Self.T
|
||||
|
||||
|
||||
def main() raises:
|
||||
# print(align_of[Aligned[Int8]]()) # 128
|
||||
# print(align_of[Aligned[Int64]]()) # 128
|
||||
|
||||
assert_equal(128, align_of[Aligned[Int8]](), "align should be 128")
|
||||
assert_equal(128, align_of[Aligned[Int64]](), "align should be 128")
|
||||
@@ -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.sys import align_of
|
||||
from std.memory import alloc, dealloc
|
||||
|
||||
|
||||
@fieldwise_init
|
||||
@align(64)
|
||||
struct CacheAligned:
|
||||
var data: Int
|
||||
|
||||
|
||||
def use_aligned():
|
||||
# Stack allocation
|
||||
var _ = CacheAligned(42) # `stack_value`
|
||||
|
||||
# Heap allocation
|
||||
var heap_alloc = alloc[CacheAligned]({count = 1})
|
||||
dealloc(heap_alloc^)
|
||||
|
||||
|
||||
def main():
|
||||
use_aligned()
|
||||
@@ -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.
|
||||
# ===----------------------------------------------------------------------=== #
|
||||
|
||||
from std.sys import align_of
|
||||
from std.testing import *
|
||||
|
||||
|
||||
@align(4)
|
||||
struct TryToReduce:
|
||||
var x: Int # Int has 8-byte natural alignment
|
||||
|
||||
|
||||
def main() raises:
|
||||
# print(align_of[TryToReduce]()) # Prints 8
|
||||
assert_equal(align_of[TryToReduce](), 8, "align should be 8")
|
||||
@@ -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 align_of, size_of
|
||||
from std.testing import *
|
||||
|
||||
|
||||
@fieldwise_init
|
||||
@align(32)
|
||||
struct AlignedTrivial(RegisterPassable):
|
||||
var value: Int
|
||||
|
||||
|
||||
def main() raises:
|
||||
# print(align_of[AlignedTrivial]()) # 32
|
||||
# print(size_of[AlignedTrivial]()) # 32
|
||||
assert_equal(32, align_of[AlignedTrivial](), "align should be 32")
|
||||
assert_equal(32, size_of[AlignedTrivial](), "size_of should be 32")
|
||||
@@ -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.
|
||||
# ===----------------------------------------------------------------------=== #
|
||||
|
||||
from std.sys import align_of
|
||||
from std.testing import *
|
||||
|
||||
|
||||
@fieldwise_init
|
||||
@align(1)
|
||||
struct MinimalAlign:
|
||||
var x: Int
|
||||
|
||||
|
||||
def main() raises:
|
||||
# print(align_of[MinimalAlign]()) # Prints 8
|
||||
assert_equal(8, align_of[MinimalAlign](), "align should be 8")
|
||||
@@ -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.
|
||||
# ===----------------------------------------------------------------------=== #
|
||||
|
||||
|
||||
# Mark function `a` as deprecated with a custom message
|
||||
@deprecated("Ignore. Deprecation test. Sunsetting a")
|
||||
def a():
|
||||
pass
|
||||
|
||||
|
||||
# Mark function `b` as deprecated with alternative
|
||||
@deprecated(use=c)
|
||||
def b():
|
||||
pass
|
||||
|
||||
|
||||
# `c` is `b`'s recommended replacement after deprecation
|
||||
def c():
|
||||
pass
|
||||
|
||||
|
||||
def main():
|
||||
a() # custom warning
|
||||
b() # warning with recommended replacement
|
||||
c() # no warning
|
||||
|
||||
# Demonstrate that only warnings are issued
|
||||
print("This is a functioning app")
|
||||
@@ -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.
|
||||
# ===----------------------------------------------------------------------=== #
|
||||
|
||||
|
||||
@deprecated(use=OtherStruct)
|
||||
@fieldwise_init
|
||||
struct MyStruct:
|
||||
var x: Int
|
||||
|
||||
|
||||
@deprecated(use=Honkable)
|
||||
trait Quackable:
|
||||
def quack(self):
|
||||
...
|
||||
|
||||
|
||||
trait Honkable:
|
||||
def honk(self):
|
||||
...
|
||||
|
||||
|
||||
struct OtherStruct:
|
||||
var x: Int
|
||||
var y: Int
|
||||
|
||||
@deprecated("Ignore. Deprecation test.")
|
||||
def function(self):
|
||||
pass
|
||||
|
||||
def __init__(out self, x: Int):
|
||||
self.x = x
|
||||
self.y = 0
|
||||
|
||||
|
||||
@deprecated("Ignore. Deprecation test.")
|
||||
comptime pi = 3.141592
|
||||
|
||||
|
||||
def main():
|
||||
_ = MyStruct(x=5)
|
||||
|
||||
OtherStruct(2).function()
|
||||
|
||||
print(pi)
|
||||
|
||||
# Demonstrate that only warnings are issued
|
||||
print("This is a functioning app")
|
||||
@@ -0,0 +1,81 @@
|
||||
# ===----------------------------------------------------------------------=== #
|
||||
# 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.
|
||||
# ===----------------------------------------------------------------------=== #
|
||||
|
||||
# TODO: Currently this file doesn't test doc output—KGEN tests
|
||||
# should do that—it only ensures that the code examples in the
|
||||
# doc are syntactically correct.
|
||||
|
||||
|
||||
@doc_hidden
|
||||
def standalone_function():
|
||||
pass
|
||||
|
||||
|
||||
struct Calculator:
|
||||
"""A simple calculator struct demonstrating @doc_hidden."""
|
||||
|
||||
var value: Int
|
||||
|
||||
def __init__(out self, initial_value: Int = 0):
|
||||
"""Creates a new Calculator with an initial value.
|
||||
|
||||
Args:
|
||||
initial_value: The starting value for the calculator. Defaults to 0.
|
||||
"""
|
||||
self.value = initial_value
|
||||
|
||||
@doc_hidden
|
||||
def __init__(out self):
|
||||
"""Internal initializer that should not appear in public documentation.
|
||||
|
||||
This constructor exists for implementation purposes but users should
|
||||
prefer the constructor that takes an initial value.
|
||||
"""
|
||||
self.value = 0
|
||||
|
||||
def add(mut self, amount: Int):
|
||||
"""Adds a value to the calculator.
|
||||
|
||||
Args:
|
||||
amount: The value to add.
|
||||
"""
|
||||
self.value += amount
|
||||
|
||||
|
||||
struct Point:
|
||||
@doc_hidden
|
||||
def __init__(out self):
|
||||
pass
|
||||
|
||||
|
||||
@doc_hidden
|
||||
struct InternalHelper:
|
||||
pass
|
||||
|
||||
|
||||
@doc_hidden
|
||||
comptime INTERNAL_CONSTANT = 42
|
||||
|
||||
|
||||
struct PublicStruct:
|
||||
@doc_hidden
|
||||
var implementation_detail: Int
|
||||
|
||||
|
||||
def main():
|
||||
# Create a calculator using the public constructor
|
||||
var calc = Calculator(10)
|
||||
|
||||
# Use the public method
|
||||
calc.add(5)
|
||||
print("Calculator value:", calc.value)
|
||||
@@ -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.math import Floorable, floor
|
||||
|
||||
|
||||
# This decorator limits the instance variable count to one
|
||||
# and creates an implicit initializer for you.
|
||||
@fieldwise_init("implicit")
|
||||
struct FlooringInt:
|
||||
var floored: Int
|
||||
|
||||
# This decorator allows implicit conversion of types
|
||||
# that can be floored (the decimal portion omitted)
|
||||
# and converted to an Integer
|
||||
@implicit
|
||||
def __init__[T: Floorable & Intable & Deinitable](out self, value: T):
|
||||
self.floored = Int(floor(value))
|
||||
|
||||
|
||||
# This function returns the stored `floored` value within
|
||||
# a `FlooringInt` instance.
|
||||
def floored(value: FlooringInt) -> Int:
|
||||
return value.floored
|
||||
|
||||
|
||||
def main():
|
||||
print(floored(FlooringInt(42))) # pass `FlooringInt` instance, output: 42
|
||||
print(floored(2)) # pass Int, without `FlooringInt` constructor, output: 2
|
||||
print(floored(52.6)) # pass Float64, output: 52
|
||||
var x = BFloat16(192.3)
|
||||
print(floored(x)) # pass BFloat, output: 192
|
||||
var y: FlooringInt = 180
|
||||
print(y.floored) # output 180
|
||||
var z: FlooringInt = 3.14159
|
||||
print(z.floored) # output: 3
|
||||
@@ -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.
|
||||
# ===----------------------------------------------------------------------=== #
|
||||
|
||||
|
||||
struct MyInt:
|
||||
var value: Int
|
||||
|
||||
@implicit
|
||||
def __init__(out self, value: Int):
|
||||
self.value = value
|
||||
|
||||
def __init__(out self, value: Float64):
|
||||
self.value = Int(value)
|
||||
|
||||
|
||||
def func(n: MyInt):
|
||||
print("MyInt value: ", n.value)
|
||||
|
||||
|
||||
def main():
|
||||
func(Int(42)) # Implicit conversion from Int: OK
|
||||
func(MyInt(Float64(4.2))) # Explicit conversion from Float64: OK
|
||||
# func(Float64(4.2)) # Error: can't convert Float64 to MyInt
|
||||
@@ -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.
|
||||
# ===----------------------------------------------------------------------=== #
|
||||
|
||||
|
||||
# start-legacy-capturing-closure
|
||||
def use_closure[func: def(Int) capturing[_] -> Int](num: Int) -> Int:
|
||||
return func(num)
|
||||
|
||||
|
||||
def create_closure():
|
||||
var x = 1
|
||||
|
||||
@__parameter
|
||||
def add(i: Int) -> Int:
|
||||
return x + i
|
||||
|
||||
var y = use_closure[add](2)
|
||||
print(y)
|
||||
|
||||
|
||||
def main():
|
||||
create_closure()
|
||||
# end-legacy-capturing-closure
|
||||
@@ -0,0 +1,401 @@
|
||||
# ===----------------------------------------------------------------------=== #
|
||||
# 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 expressions.mdx code examples.
|
||||
#
|
||||
# Not tested (intentional errors, type-only forms, or interactive
|
||||
# constructs):
|
||||
# - Set/dict mix errors (`{"a": 1, 2}`, `{1, "b": 2}`)
|
||||
# - Positional-after-keyword call error
|
||||
# - Duplicate keyword call error
|
||||
# - `comptime` without parentheses (intentional error)
|
||||
# - `input()` walrus example (interactive)
|
||||
# - Function type expressions (`def() -> Int`, etc.) are type-level
|
||||
# forms with no standalone runtime behavior to assert
|
||||
# - `type_of`, `conforms_to`, `origin_of` return compiler-internal
|
||||
# types per the doc; they're exercised via `where` clauses
|
||||
# elsewhere in the test corpus
|
||||
# - Identifier expressions section (bare names, not standalone code)
|
||||
from std.collections import Set
|
||||
from std.testing import assert_equal
|
||||
|
||||
|
||||
# --- Parenthesized expressions ---
|
||||
|
||||
|
||||
def test_paren_precedence() raises:
|
||||
var a = 2
|
||||
var b = 3
|
||||
var c = 4
|
||||
assert_equal((a + b) * c, 20)
|
||||
|
||||
|
||||
def test_paren_multiline() raises:
|
||||
var first_value = 1
|
||||
var second_value = 2
|
||||
var third_value = 3
|
||||
var result = first_value + second_value + third_value
|
||||
assert_equal(result, 6)
|
||||
|
||||
|
||||
# --- Tuples ---
|
||||
|
||||
|
||||
def test_tuple_by_comma() raises:
|
||||
var a = 2, 3
|
||||
var b = (2, 3)
|
||||
assert_equal(a[0], 2)
|
||||
assert_equal(a[1], 3)
|
||||
assert_equal(b[0], 2)
|
||||
assert_equal(b[1], 3)
|
||||
|
||||
|
||||
def test_tuple_destructuring() raises:
|
||||
var b = (2, 3)
|
||||
var x, y = b
|
||||
assert_equal(x, 2)
|
||||
assert_equal(y, 3)
|
||||
|
||||
|
||||
def test_tuple_one_element() raises:
|
||||
var one_tup = (1,)
|
||||
var three_tup = (1, 2, 3)
|
||||
assert_equal(one_tup[0], 1)
|
||||
assert_equal(three_tup[0], 1)
|
||||
assert_equal(three_tup[2], 3)
|
||||
|
||||
|
||||
def test_tuple_indexing() raises:
|
||||
var point = (10, 20)
|
||||
assert_equal(point[0], 10)
|
||||
assert_equal(point[1], 20)
|
||||
|
||||
|
||||
# --- Collection displays ---
|
||||
|
||||
|
||||
def test_list_display() raises:
|
||||
var numbers = [1, 2, 3]
|
||||
var strings = [
|
||||
"one",
|
||||
"two",
|
||||
"three",
|
||||
] # trailing comma allowed
|
||||
var empty: List[Float32] = []
|
||||
assert_equal(len(numbers), 3)
|
||||
assert_equal(numbers[0], 1)
|
||||
assert_equal(strings[2], "three")
|
||||
assert_equal(len(empty), 0)
|
||||
|
||||
|
||||
def test_list_display_with_expressions() raises:
|
||||
var values = [1, 1 + 1, 1 + 1 + 1]
|
||||
assert_equal(values[0], 1)
|
||||
assert_equal(values[1], 2)
|
||||
assert_equal(values[2], 3)
|
||||
|
||||
|
||||
def test_dict_display() raises:
|
||||
var ages = {"Alice": 30, "Bob": 25}
|
||||
var empty: Dict[String, Int] = {}
|
||||
assert_equal(ages["Alice"], 30)
|
||||
assert_equal(ages["Bob"], 25)
|
||||
assert_equal(len(empty), 0)
|
||||
|
||||
|
||||
def test_set_display() raises:
|
||||
var primes = {2, 3, 5, 7}
|
||||
assert_equal(len(primes), 4)
|
||||
assert_equal(2 in primes, True)
|
||||
assert_equal(4 in primes, False)
|
||||
|
||||
|
||||
def test_set_explicit_type() raises:
|
||||
# Set displays are built-in syntax, but naming the `Set` type needs the
|
||||
# import at the top of this file.
|
||||
var display_set = {1, 2, 3} # set display, no import needed
|
||||
assert_equal(len(display_set), 3)
|
||||
|
||||
var empty_set = Set[Int]() # naming Set[Int] requires the import
|
||||
empty_set.add(4)
|
||||
empty_set.add(4) # adding a duplicate is a no-op
|
||||
assert_equal(len(empty_set), 1)
|
||||
|
||||
|
||||
# --- Initializer lists ---
|
||||
|
||||
|
||||
@fieldwise_init
|
||||
struct Pair(Copyable, Movable):
|
||||
var a: Int
|
||||
var b: String
|
||||
|
||||
|
||||
def process(p: Pair) -> String:
|
||||
return p.b
|
||||
|
||||
|
||||
def test_initializer_list_call() raises:
|
||||
# `{1, "hello"}` is sugar for `Pair(1, "hello")` when type is inferred.
|
||||
assert_equal(process({1, "hello"}), "hello")
|
||||
|
||||
|
||||
def test_initializer_list_keyword() raises:
|
||||
var p: Pair = {a = 7, b = "kw"}
|
||||
assert_equal(p.a, 7)
|
||||
assert_equal(p.b, "kw")
|
||||
|
||||
|
||||
# --- Member access ---
|
||||
|
||||
|
||||
@fieldwise_init
|
||||
struct Point2(Copyable, Movable):
|
||||
var x: Int
|
||||
var y: Int
|
||||
|
||||
|
||||
def test_member_access() raises:
|
||||
var p = Point2(10, 20)
|
||||
assert_equal(p.x, 10)
|
||||
assert_equal(p.y, 20)
|
||||
|
||||
|
||||
# --- Calls (positional and keyword arguments) ---
|
||||
|
||||
|
||||
def greet(name: String, loud: Bool = False) -> String:
|
||||
return String("HELLO, ").upper() if loud else String("Hello, ") + name
|
||||
|
||||
|
||||
def add(a: Int, b: Int) -> Int:
|
||||
return a + b
|
||||
|
||||
|
||||
def test_call_positional() raises:
|
||||
assert_equal(add(2, 3), 5)
|
||||
|
||||
|
||||
def test_call_keyword() raises:
|
||||
assert_equal(add(a=2, b=3), 5)
|
||||
|
||||
|
||||
def test_call_mixed_with_default() raises:
|
||||
assert_equal(greet("Alice"), "Hello, Alice")
|
||||
assert_equal(greet("Alice", loud=True), "HELLO, ")
|
||||
assert_equal(greet(name="Bob"), "Hello, Bob")
|
||||
|
||||
|
||||
# --- Subscripts and slices ---
|
||||
|
||||
|
||||
def test_subscript_list() raises:
|
||||
var items = [10, 20, 30]
|
||||
assert_equal(items[0], 10)
|
||||
assert_equal(items[2], 30)
|
||||
|
||||
|
||||
def test_subscript_dict() raises:
|
||||
var mapping = {"key": 42}
|
||||
assert_equal(mapping["key"], 42)
|
||||
|
||||
|
||||
def test_slice_start_stop() raises:
|
||||
var items: List = [0, 1, 2, 3, 4, 5]
|
||||
var first_three = items[0:3]
|
||||
assert_equal(len(first_three), 3)
|
||||
assert_equal(first_three[0], 0)
|
||||
assert_equal(first_three[2], 2)
|
||||
|
||||
|
||||
def test_slice_open_stop() raises:
|
||||
var items: List = [0, 1, 2, 3, 4, 5]
|
||||
var from_three = items[3:]
|
||||
assert_equal(len(from_three), 3)
|
||||
assert_equal(from_three[0], 3)
|
||||
assert_equal(from_three[2], 5)
|
||||
|
||||
|
||||
def test_slice_stride() raises:
|
||||
var items: List = [0, 1, 2, 3, 4, 5]
|
||||
var every_other = items[::2]
|
||||
assert_equal(len(every_other), 3)
|
||||
assert_equal(every_other[0], 0)
|
||||
assert_equal(every_other[1], 2)
|
||||
assert_equal(every_other[2], 4)
|
||||
|
||||
|
||||
def test_slice_negative_stride() raises:
|
||||
var items: List = [0, 1, 2, 3, 4, 5]
|
||||
var reversed_items = items[::-1]
|
||||
assert_equal(len(reversed_items), 6)
|
||||
assert_equal(reversed_items[0], 5)
|
||||
assert_equal(reversed_items[5], 0)
|
||||
|
||||
|
||||
# --- Ternary conditional ---
|
||||
|
||||
|
||||
def test_ternary_basic() raises:
|
||||
var x = 4
|
||||
var label = "even" if x % 2 == 0 else "odd"
|
||||
assert_equal(label, "even")
|
||||
x = 5
|
||||
label = "even" if x % 2 == 0 else "odd"
|
||||
assert_equal(label, "odd")
|
||||
|
||||
|
||||
def test_ternary_chained_right_assoc() raises:
|
||||
# Parses as: "small" if n < 10 else ("large" if n > 100 else "medium")
|
||||
def size(n: Int) -> String:
|
||||
return "small" if n < 10 else "large" if n > 100 else "medium"
|
||||
|
||||
assert_equal(size(5), "small")
|
||||
assert_equal(size(50), "medium")
|
||||
assert_equal(size(500), "large")
|
||||
|
||||
|
||||
# --- Walrus operator ---
|
||||
|
||||
|
||||
def test_walrus_in_if() raises:
|
||||
var items = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
|
||||
var captured: Int = -1
|
||||
var n: Int
|
||||
if (n := len(items)) > 10:
|
||||
captured = n
|
||||
assert_equal(captured, 11)
|
||||
|
||||
|
||||
def test_walrus_in_while() raises:
|
||||
var i = 0
|
||||
var last_seen: Int = -1
|
||||
var j: Int
|
||||
while (j := i) < 3:
|
||||
last_seen = j
|
||||
i += 1
|
||||
assert_equal(last_seen, 2)
|
||||
|
||||
|
||||
# --- Compile-time expressions ---
|
||||
|
||||
|
||||
def heavy_calculation() -> Int:
|
||||
var sum = 0
|
||||
for i in range(1_000_000):
|
||||
sum += i
|
||||
return sum
|
||||
|
||||
|
||||
def test_comptime_expression() raises:
|
||||
var x = comptime (heavy_calculation())
|
||||
assert_equal(x, 499_999_500_000)
|
||||
|
||||
|
||||
# --- Comprehensions ---
|
||||
|
||||
|
||||
def test_list_comprehension_with_filter() raises:
|
||||
var squares = [x * x for x in [0, 1, 2, 3, 4] if x % 2 == 0]
|
||||
assert_equal(len(squares), 3)
|
||||
assert_equal(squares[0], 0)
|
||||
assert_equal(squares[1], 4)
|
||||
assert_equal(squares[2], 16)
|
||||
|
||||
|
||||
def test_list_comprehension_over_range() raises:
|
||||
var positive = [x for x in range(-3, 3) if x > 0]
|
||||
assert_equal(len(positive), 2)
|
||||
assert_equal(positive[0], 1)
|
||||
assert_equal(positive[1], 2)
|
||||
|
||||
|
||||
def fib(n: Int) -> Int:
|
||||
# fib(0)=1, fib(1)=1, fib(2)=2, fib(3)=3, fib(4)=5, fib(5)=8
|
||||
if n < 2:
|
||||
return 1
|
||||
var a = 2
|
||||
var b = 3
|
||||
for _ in range(n - 2):
|
||||
(a, b) = (b, a + b)
|
||||
return a
|
||||
|
||||
|
||||
def test_set_comprehension() raises:
|
||||
var fibs = {fib(x) for x in range(6)}
|
||||
# 6 iterations produce {1, 2, 3, 5, 8} after dedup
|
||||
assert_equal(len(fibs), 5)
|
||||
assert_equal(1 in fibs, True)
|
||||
assert_equal(8 in fibs, True)
|
||||
|
||||
|
||||
def test_dict_comprehension_basic() raises:
|
||||
var dict_squares = {x: x * x for x in range(3)}
|
||||
assert_equal(len(dict_squares), 3)
|
||||
assert_equal(dict_squares[0], 0)
|
||||
assert_equal(dict_squares[1], 1)
|
||||
assert_equal(dict_squares[2], 4)
|
||||
|
||||
|
||||
def test_dict_comprehension_string_keys() raises:
|
||||
var lengths: Dict[String, Int] = {
|
||||
k: k.byte_length() for k in ["one", "two", "three", "four"]
|
||||
}
|
||||
assert_equal(lengths["one"], 3)
|
||||
assert_equal(lengths["three"], 5)
|
||||
assert_equal(lengths["four"], 4)
|
||||
|
||||
|
||||
def test_multi_clause_comprehension() raises:
|
||||
var products = [
|
||||
(x, y, x * y) for x in range(3) for y in range(3) if (x + y) % 2 == 0
|
||||
]
|
||||
# Expected: [(0,0,0), (0,2,0), (1,1,1), (2,0,0), (2,2,4)]
|
||||
assert_equal(len(products), 5)
|
||||
|
||||
|
||||
def main() raises:
|
||||
test_paren_precedence()
|
||||
test_paren_multiline()
|
||||
test_tuple_by_comma()
|
||||
test_tuple_destructuring()
|
||||
test_tuple_one_element()
|
||||
test_tuple_indexing()
|
||||
test_list_display()
|
||||
test_list_display_with_expressions()
|
||||
test_dict_display()
|
||||
test_set_display()
|
||||
test_set_explicit_type()
|
||||
test_initializer_list_call()
|
||||
test_initializer_list_keyword()
|
||||
test_member_access()
|
||||
test_call_positional()
|
||||
test_call_keyword()
|
||||
test_call_mixed_with_default()
|
||||
test_subscript_list()
|
||||
test_subscript_dict()
|
||||
test_slice_start_stop()
|
||||
test_slice_open_stop()
|
||||
test_slice_stride()
|
||||
test_slice_negative_stride()
|
||||
test_ternary_basic()
|
||||
test_ternary_chained_right_assoc()
|
||||
test_walrus_in_if()
|
||||
test_walrus_in_while()
|
||||
test_comptime_expression()
|
||||
test_list_comprehension_with_filter()
|
||||
test_list_comprehension_over_range()
|
||||
test_set_comprehension()
|
||||
test_dict_comprehension_basic()
|
||||
test_dict_comprehension_string_keys()
|
||||
test_multi_clause_comprehension()
|
||||
@@ -0,0 +1,565 @@
|
||||
# ===----------------------------------------------------------------------=== #
|
||||
# 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_function_declarations.mojo
|
||||
# Tests for function-declarations.mdx code examples.
|
||||
# Skip: inferred_type[Int](5) positional error, keyword type
|
||||
# mismatch error, div keyword error, configure positional
|
||||
# error, sum missing keyword error, bad default ordering
|
||||
# error, mut default error, out + return type error,
|
||||
# variadic default error, out variadic error, __init__
|
||||
# without out error, where on runtime arg error,
|
||||
# Resource/__deinit__ (undefined _release), parse/parse_strict
|
||||
# (signature-only stubs), copy/move constructor snippets
|
||||
# (no enclosing struct), configure keyword-only (pass-only
|
||||
# body), overload-set import-shadowing snippet (fictional
|
||||
# `from somewhere import add` - hand tested), ambiguous overload
|
||||
# call `foo("Hello")` (negative example, exercised by the
|
||||
# disambiguation test instead), return-type-only overload
|
||||
# of `parse` (negative example: `redefinition of function
|
||||
# 'parse': cannot overload on return type only`),
|
||||
# raises-only overload of `maybe_raise` (negative example:
|
||||
# `redefinition of function 'maybe_raise' with identical
|
||||
# signature` - hand tested), literal-conversion ambiguity
|
||||
# of `take_param[1, 2]()` against `[Int, Int]` vs
|
||||
# `[Int, Float64]` (negative example; the runnable
|
||||
# `take_param` test uses `[Int, String]` instead),
|
||||
# unguarded `var self` on a `TrivialRegisterPassable` type
|
||||
# (sharp edge: `^` is a no-op for TRP, so `(c^).which()`
|
||||
# returns the `ref self` value - hand verified; the runnable
|
||||
# test instead uses `where not conforms_to(Self,
|
||||
# TrivialRegisterPassable)` to filter the overload out).
|
||||
from std.testing import assert_equal
|
||||
from std.reflection import reflect
|
||||
|
||||
|
||||
# --- Basic function ---
|
||||
|
||||
|
||||
def greet(name: String) -> String:
|
||||
return "Hello, " + name
|
||||
|
||||
|
||||
def test_greet() raises:
|
||||
assert_equal(greet("Mojo"), "Hello, Mojo")
|
||||
|
||||
|
||||
# --- Minimal function ---
|
||||
|
||||
|
||||
def do_nothing():
|
||||
pass
|
||||
|
||||
|
||||
def test_do_nothing():
|
||||
do_nothing()
|
||||
|
||||
|
||||
# --- Backtick-escaped name ---
|
||||
|
||||
|
||||
def `import`():
|
||||
print("In `import`")
|
||||
|
||||
|
||||
def test_backtick_name():
|
||||
`import`() # In `import`
|
||||
|
||||
|
||||
# --- Parameterized function ---
|
||||
|
||||
|
||||
def clamp[
|
||||
T: Comparable & ImplicitlyCopyable
|
||||
](val: T, lo: T, hi: T,) -> T:
|
||||
if val < lo:
|
||||
return lo
|
||||
if val > hi:
|
||||
return hi
|
||||
return val
|
||||
|
||||
|
||||
def test_clamp() raises:
|
||||
assert_equal(clamp(5, 1, 10), 5)
|
||||
assert_equal(clamp(-3, 1, 10), 1)
|
||||
assert_equal(clamp(99, 1, 10), 10)
|
||||
|
||||
|
||||
# --- Infer-only marker (//) ---
|
||||
|
||||
|
||||
def inferred_type[T: Writable, //](value: T):
|
||||
print(t"Value is {value}. Type is {reflect[T].name()}.")
|
||||
|
||||
|
||||
def test_inferred_type():
|
||||
inferred_type(5) # Value is 5. Type is Int.
|
||||
inferred_type("Hello") # Value is Hello. Type is String.
|
||||
|
||||
|
||||
# --- Keyword bypass for infer-only ---
|
||||
|
||||
|
||||
def test_inferred_type_keyword():
|
||||
inferred_type[T=Int](5) # Value is 5. Type is Int.
|
||||
|
||||
|
||||
# --- Parameter inference ---
|
||||
|
||||
|
||||
def add[T: Intable](a: T, b: T) -> Int:
|
||||
return Int(a) + Int(b)
|
||||
|
||||
|
||||
def test_add() raises:
|
||||
assert_equal(add[Int](1, 2), 3)
|
||||
assert_equal(add(1, 2), 3)
|
||||
assert_equal(add[Float64](4.5, 1.2), 5)
|
||||
assert_equal(add(4.5, 1.2), 5)
|
||||
|
||||
|
||||
# --- Positional-only marker (/) ---
|
||||
|
||||
|
||||
def div(a: Int, b: Int, /) -> Int:
|
||||
return a // b
|
||||
|
||||
|
||||
def test_positional_only() raises:
|
||||
assert_equal(div(10, 3), 3)
|
||||
|
||||
|
||||
# --- Variadic with keyword-only ---
|
||||
|
||||
|
||||
def sum_kw(*values: Int, name: String) -> Int:
|
||||
print(name, end=": ")
|
||||
var total = 0
|
||||
for value in values:
|
||||
total += value
|
||||
return total
|
||||
|
||||
|
||||
def test_variadic_keyword() raises:
|
||||
assert_equal(sum_kw(1, 2, 3, name="total"), 6) # total: 6
|
||||
|
||||
|
||||
# --- Default values ---
|
||||
|
||||
|
||||
def connect(
|
||||
host: String = "www.modular.com",
|
||||
port: Int = 80,
|
||||
):
|
||||
print(t"Connecting to {host}:{port}")
|
||||
|
||||
|
||||
def test_defaults():
|
||||
connect() # Connecting to www.modular.com:80
|
||||
connect(port=8080) # Connecting to www.modular.com:8080
|
||||
|
||||
|
||||
# --- Defaults with return ---
|
||||
|
||||
|
||||
def my_function(x: Int, y: Int = 0, z: Int = 0) -> Int:
|
||||
return x + y + z
|
||||
|
||||
|
||||
def test_defaults_return() raises:
|
||||
assert_equal(my_function(1), 1)
|
||||
assert_equal(my_function(1, 2), 3)
|
||||
assert_equal(my_function(1, 2, 3), 6)
|
||||
|
||||
|
||||
# --- Where clause on parameter ---
|
||||
|
||||
|
||||
def process[
|
||||
n: Int
|
||||
](data: SIMD[.float32, n]) -> Float32 where (
|
||||
n == 1 or n == 2 or n == 4 or n == 8 or n == 16 or n == 32
|
||||
):
|
||||
var sum: Float32 = 0.0
|
||||
for i in range(n):
|
||||
sum += data[i]
|
||||
return sum
|
||||
|
||||
|
||||
def test_where_clause() raises:
|
||||
var data = SIMD[.float32, 16](255.0)
|
||||
var sum = process[n=16](data)
|
||||
assert_equal(sum, 4080.0)
|
||||
|
||||
|
||||
# --- Where with conforms_to ---
|
||||
|
||||
|
||||
comptime LESS_THAN: Int32 = -1
|
||||
comptime EQUAL: Int32 = 0
|
||||
comptime GREATER_THAN: Int32 = 1
|
||||
|
||||
|
||||
def compare[
|
||||
T: AnyType
|
||||
](x: T, y: T,) -> Int32 where conforms_to(T, Comparable):
|
||||
if x < y:
|
||||
return LESS_THAN
|
||||
elif x > y:
|
||||
return GREATER_THAN
|
||||
else:
|
||||
return EQUAL
|
||||
|
||||
|
||||
def test_compare() raises:
|
||||
assert_equal(compare(5, 10), -1)
|
||||
assert_equal(compare(7, 7), 0)
|
||||
assert_equal(compare("Z", "A"), 1)
|
||||
|
||||
|
||||
# --- mut convention ---
|
||||
|
||||
|
||||
def double_it(mut x: Int):
|
||||
x *= 2
|
||||
|
||||
|
||||
def test_mut() raises:
|
||||
var x = 5
|
||||
double_it(x)
|
||||
assert_equal(x, 10)
|
||||
|
||||
|
||||
# --- var convention ---
|
||||
|
||||
|
||||
def consume(var s: String):
|
||||
s += "!"
|
||||
print(s)
|
||||
|
||||
|
||||
def test_var_convention() raises:
|
||||
var greeting = "Hello"
|
||||
consume(greeting) # Hello! (copied)
|
||||
assert_equal(greeting, "Hello")
|
||||
|
||||
consume(greeting^) # Hello! (moved)
|
||||
# greeting is now inaccessible
|
||||
|
||||
|
||||
# --- out convention ---
|
||||
|
||||
|
||||
def make_int(out result: Int):
|
||||
result = 42
|
||||
|
||||
|
||||
def test_out() raises:
|
||||
var x = make_int()
|
||||
assert_equal(x, 42)
|
||||
|
||||
|
||||
# --- ref convention ---
|
||||
|
||||
|
||||
def get_first[T: Copyable](ref data: List[T]) -> ref[data[0]] T:
|
||||
return data[0]
|
||||
|
||||
|
||||
def test_ref() raises:
|
||||
var data: List = ["one", "two", "three"]
|
||||
ref first = get_first(data)
|
||||
assert_equal(first, "one")
|
||||
first = "Первый"
|
||||
assert_equal(data[0], "Первый")
|
||||
|
||||
|
||||
# --- Default convention ---
|
||||
|
||||
|
||||
def length[T: Copyable](s: List[T]) -> Int:
|
||||
return len(s)
|
||||
|
||||
|
||||
def test_default_convention() raises:
|
||||
assert_equal(length(["M", "o", "j", "o"]), 4)
|
||||
|
||||
|
||||
# --- Homogeneous variadics ---
|
||||
|
||||
|
||||
def sum_all(*values: Int) -> Int:
|
||||
var total = 0
|
||||
for v in values:
|
||||
total += v
|
||||
return total
|
||||
|
||||
|
||||
def test_homogeneous_variadics() raises:
|
||||
assert_equal(sum_all(1, 2, 3), 6)
|
||||
assert_equal(sum_all(10, 20), 30)
|
||||
|
||||
|
||||
# --- Variadic packs ---
|
||||
|
||||
|
||||
def print_all[*Ts: Writable](*args: *Ts):
|
||||
comptime for idx in range(args.__len__()):
|
||||
print(args[idx], end=" ")
|
||||
print()
|
||||
|
||||
|
||||
def test_variadic_packs():
|
||||
print_all("Hello", 42, 3.14) # Hello 42 3.14
|
||||
|
||||
|
||||
# --- thin function effect ---
|
||||
|
||||
|
||||
def map_thin[
|
||||
T: Copyable, U: Copyable
|
||||
](f: def(T) thin -> U, input: List[T]) -> List[U]:
|
||||
var result: List[U] = []
|
||||
for item in input:
|
||||
result.append(f(item))
|
||||
return result^
|
||||
|
||||
|
||||
def square_thin(x: Int) -> Int:
|
||||
return x * x
|
||||
|
||||
|
||||
def test_thin() raises:
|
||||
var nums: List[Int] = [1, 2, 3]
|
||||
var squares = map_thin(square_thin, nums)
|
||||
assert_equal(squares[0], 1)
|
||||
assert_equal(squares[1], 4)
|
||||
assert_equal(squares[2], 9)
|
||||
|
||||
|
||||
# --- Return type ---
|
||||
|
||||
|
||||
def square(x: Int) -> Int:
|
||||
return x * x
|
||||
|
||||
|
||||
def test_square() raises:
|
||||
assert_equal(square(5), 25)
|
||||
|
||||
|
||||
# --- Nested functions ---
|
||||
|
||||
|
||||
def outer(x: Int) -> Int:
|
||||
def inner() {imm} -> Int:
|
||||
return x + 1
|
||||
|
||||
return inner()
|
||||
|
||||
|
||||
def test_nested() raises:
|
||||
assert_equal(outer(5), 6)
|
||||
|
||||
|
||||
# --- Static methods ---
|
||||
|
||||
|
||||
struct MathUtils:
|
||||
comptime pi: Float64 = 3.141592653589793
|
||||
|
||||
@staticmethod
|
||||
def square(x: Int) -> Int:
|
||||
return x * x
|
||||
|
||||
|
||||
def test_static_methods() raises:
|
||||
assert_equal(MathUtils.square(5), 25)
|
||||
|
||||
|
||||
# --- Function overloads: basic ---
|
||||
|
||||
|
||||
def add_pair(x: Int, y: Int) -> Int:
|
||||
return x + y
|
||||
|
||||
|
||||
def add_pair(x: String, y: String) -> String:
|
||||
return x + y
|
||||
|
||||
|
||||
def test_add_pair() raises:
|
||||
assert_equal(add_pair(1, 2), 3)
|
||||
assert_equal(add_pair("Hi, ", "Mojo"), "Hi, Mojo")
|
||||
|
||||
|
||||
# --- Overloading parameters ---
|
||||
|
||||
|
||||
def take_param[a: Int, b: Int]() -> String:
|
||||
return "take_param[a: Int, b: Int]"
|
||||
|
||||
|
||||
def take_param[a: Int, b: String]() -> String:
|
||||
return "take_param[a: Int, b: String]"
|
||||
|
||||
|
||||
def test_take_param() raises:
|
||||
assert_equal(take_param[1, 2](), "take_param[a: Int, b: Int]")
|
||||
assert_equal(take_param[1, "hi"](), "take_param[a: Int, b: String]")
|
||||
|
||||
|
||||
# --- Overloading the `self` convention ---
|
||||
|
||||
|
||||
@fieldwise_init
|
||||
struct Counter(Copyable):
|
||||
var n: Int
|
||||
|
||||
def which(ref self) -> Int:
|
||||
return 1
|
||||
|
||||
# Constrain `var self` to types where `^` actually transfers.
|
||||
# For `TrivialRegisterPassable` types, `^` is a no-op, so this
|
||||
# overload would otherwise be silently unreachable.
|
||||
def which(
|
||||
var self,
|
||||
) -> Int where not conforms_to(Self, TrivialRegisterPassable):
|
||||
return 2
|
||||
|
||||
|
||||
@fieldwise_init
|
||||
struct CounterRegister(ImplicitlyCopyable, TrivialRegisterPassable):
|
||||
var n: Int
|
||||
|
||||
def which(ref self) -> Int:
|
||||
return 1
|
||||
|
||||
# Same constraint here: the `where` clause filters out this
|
||||
# overload entirely for `TrivialRegisterPassable` types.
|
||||
def which(
|
||||
var self,
|
||||
) -> Int where not conforms_to(Self, TrivialRegisterPassable):
|
||||
return 2
|
||||
|
||||
|
||||
def test_self_convention_overload() raises:
|
||||
# Non-TRP: both overloads reachable
|
||||
var c1 = Counter(0)
|
||||
assert_equal(c1.which(), 1) # default call borrows -> ref self
|
||||
|
||||
var c2 = Counter(0)
|
||||
assert_equal((c2^).which(), 2) # transfer at call site -> var self
|
||||
|
||||
# TRP: the `var self` overload is excluded by `where`, so only
|
||||
# `ref self` matches any call.
|
||||
var r1 = CounterRegister(0)
|
||||
assert_equal(r1.which(), 1)
|
||||
|
||||
|
||||
# --- Instance methods beat static methods ---
|
||||
|
||||
|
||||
struct StaticOverload:
|
||||
def __init__(out self):
|
||||
pass
|
||||
|
||||
def foo(mut self) -> String:
|
||||
return "instance method"
|
||||
|
||||
@staticmethod
|
||||
def foo() -> String:
|
||||
return "static method"
|
||||
|
||||
|
||||
def test_instance_beats_static() raises:
|
||||
var a = StaticOverload()
|
||||
assert_equal(a.foo(), "instance method")
|
||||
assert_equal(StaticOverload.foo(), "static method")
|
||||
|
||||
|
||||
# --- Variadic candidates lose ties ---
|
||||
|
||||
|
||||
def take_one_or_many(x: Int) -> String:
|
||||
return "take(x: Int)"
|
||||
|
||||
|
||||
def take_one_or_many(*xs: Int) -> String:
|
||||
return "take(*xs: Int)"
|
||||
|
||||
|
||||
def test_variadic_ties() raises:
|
||||
assert_equal(take_one_or_many(1), "take(x: Int)")
|
||||
assert_equal(take_one_or_many(1, 2, 3), "take(*xs: Int)")
|
||||
|
||||
|
||||
# --- Ambiguity, resolved by cast ---
|
||||
|
||||
|
||||
struct MyString:
|
||||
@implicit
|
||||
def __init__(out self, s: String):
|
||||
pass
|
||||
|
||||
|
||||
struct YourString:
|
||||
@implicit
|
||||
def __init__(out self, s: String):
|
||||
pass
|
||||
|
||||
|
||||
def overloaded_str(name: MyString) -> String:
|
||||
return "MyString"
|
||||
|
||||
|
||||
def overloaded_str(name: YourString) -> String:
|
||||
return "YourString"
|
||||
|
||||
|
||||
def test_ambiguity_resolved_by_cast() raises:
|
||||
# overloaded_str("Hello") would be ambiguous: skipped intentionally.
|
||||
assert_equal(overloaded_str(MyString("Hello")), "MyString")
|
||||
assert_equal(overloaded_str(YourString("Hello")), "YourString")
|
||||
|
||||
|
||||
def main() raises:
|
||||
test_greet()
|
||||
test_do_nothing()
|
||||
test_backtick_name()
|
||||
test_clamp()
|
||||
test_inferred_type()
|
||||
test_inferred_type_keyword()
|
||||
test_add()
|
||||
test_positional_only()
|
||||
test_variadic_keyword()
|
||||
test_defaults()
|
||||
test_defaults_return()
|
||||
test_where_clause()
|
||||
test_compare()
|
||||
test_mut()
|
||||
test_var_convention()
|
||||
test_out()
|
||||
test_ref()
|
||||
test_default_convention()
|
||||
test_homogeneous_variadics()
|
||||
test_variadic_packs()
|
||||
test_thin()
|
||||
test_square()
|
||||
test_nested()
|
||||
test_static_methods()
|
||||
test_add_pair()
|
||||
test_take_param()
|
||||
test_self_convention_overload()
|
||||
test_instance_beats_static()
|
||||
test_variadic_ties()
|
||||
test_ambiguity_resolved_by_cast()
|
||||
@@ -0,0 +1,486 @@
|
||||
# ===----------------------------------------------------------------------=== #
|
||||
# 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_inline_mlir.mojo
|
||||
# Tests for inline-mlir.mdx code examples.
|
||||
from std.testing import assert_equal
|
||||
|
||||
|
||||
# --- Your first inline MLIR ---
|
||||
|
||||
|
||||
def test_hello_mlir() raises:
|
||||
"""Three builtins working together: type, attr, op."""
|
||||
var a: __mlir_type.index = __mlir_attr.`42 : index`
|
||||
var b: __mlir_type.index = __mlir_attr.`8 : index`
|
||||
var c = __mlir_op.`index.add`(a, b)
|
||||
assert_equal(Int(mlir_value=c), 50)
|
||||
|
||||
|
||||
# --- __mlir_type ---
|
||||
|
||||
|
||||
def test_mlir_type_dot_syntax() raises:
|
||||
"""Dot syntax for simple MLIR type names."""
|
||||
var x: __mlir_type.i1 = __mlir_attr.true
|
||||
var y: __mlir_type.index = __mlir_attr.`0 : index`
|
||||
assert_equal(Bool(x), True)
|
||||
assert_equal(Int(mlir_value=y), 0)
|
||||
|
||||
|
||||
def test_mlir_type_backtick_syntax() raises:
|
||||
"""Backtick syntax for dialect types with special characters."""
|
||||
var s: __mlir_type.`!kgen.scalar<index>` = (
|
||||
__mlir_op.`pop.cast_from_builtin`[
|
||||
_type=__mlir_type.`!kgen.scalar<index>`
|
||||
](__mlir_attr.`7 : index`)
|
||||
)
|
||||
var result = __mlir_op.`pop.cast_to_builtin`[_type=__mlir_type.index](s)
|
||||
assert_equal(Int(mlir_value=result), 7)
|
||||
|
||||
|
||||
# --- __mlir_attr ---
|
||||
|
||||
|
||||
def test_mlir_attr_bool() raises:
|
||||
"""Boolean attributes: true and false."""
|
||||
var t: __mlir_type.i1 = __mlir_attr.true
|
||||
var f: __mlir_type.i1 = __mlir_attr.false
|
||||
assert_equal(Bool(t), True)
|
||||
assert_equal(Bool(f), False)
|
||||
|
||||
|
||||
def test_mlir_attr_typed_constants() raises:
|
||||
"""Backtick syntax for typed integer constants."""
|
||||
var zero: __mlir_type.index = __mlir_attr.`0 : index`
|
||||
var forty_two: __mlir_type.index = __mlir_attr.`42 : index`
|
||||
var negative: __mlir_type.index = __mlir_attr.`-1 : index`
|
||||
assert_equal(Int(mlir_value=zero), 0)
|
||||
assert_equal(Int(mlir_value=forty_two), 42)
|
||||
assert_equal(Int(mlir_value=negative), -1)
|
||||
|
||||
|
||||
# --- __mlir_op: index dialect ---
|
||||
|
||||
|
||||
def test_index_arithmetic() raises:
|
||||
"""Index dialect: add, sub, mul, divs."""
|
||||
var a: __mlir_type.index = __mlir_attr.`10 : index`
|
||||
var b: __mlir_type.index = __mlir_attr.`3 : index`
|
||||
|
||||
var sum = __mlir_op.`index.add`(a, b)
|
||||
assert_equal(Int(mlir_value=sum), 13)
|
||||
|
||||
var diff = __mlir_op.`index.sub`(a, b)
|
||||
assert_equal(Int(mlir_value=diff), 7)
|
||||
|
||||
var prod = __mlir_op.`index.mul`(a, b)
|
||||
assert_equal(Int(mlir_value=prod), 30)
|
||||
|
||||
var quot = __mlir_op.`index.divs`(a, b)
|
||||
assert_equal(Int(mlir_value=quot), 3)
|
||||
|
||||
|
||||
def test_index_bitwise() raises:
|
||||
"""Index dialect: and, or, xor, shl, shrs."""
|
||||
var a: __mlir_type.index = __mlir_attr.`10 : index` # 0b1010
|
||||
var b: __mlir_type.index = __mlir_attr.`12 : index` # 0b1100
|
||||
|
||||
var and_result = __mlir_op.`index.and`(a, b)
|
||||
assert_equal(Int(mlir_value=and_result), 0b1000) # 8
|
||||
|
||||
var or_result = __mlir_op.`index.or`(a, b)
|
||||
assert_equal(Int(mlir_value=or_result), 0b1110) # 14
|
||||
|
||||
var xor_result = __mlir_op.`index.xor`(a, b)
|
||||
assert_equal(Int(mlir_value=xor_result), 0b0110) # 6
|
||||
|
||||
var one: __mlir_type.index = __mlir_attr.`1 : index`
|
||||
var shifted = __mlir_op.`index.shl`(a, one)
|
||||
assert_equal(Int(mlir_value=shifted), 0b10100) # 20
|
||||
|
||||
var rshifted = __mlir_op.`index.shrs`(a, one)
|
||||
assert_equal(Int(mlir_value=rshifted), 0b0101) # 5
|
||||
|
||||
|
||||
def test_index_comparisons() raises:
|
||||
"""Index dialect: cmp with various predicates."""
|
||||
var five: __mlir_type.index = __mlir_attr.`5 : index`
|
||||
var ten: __mlir_type.index = __mlir_attr.`10 : index`
|
||||
|
||||
var lt = __mlir_op.`index.cmp`[
|
||||
pred=__mlir_attr.`#index.cmp_predicate<slt>`
|
||||
](five, ten)
|
||||
assert_equal(Bool(lt), True)
|
||||
|
||||
var eq = __mlir_op.`index.cmp`[pred=__mlir_attr.`#index.cmp_predicate<eq>`](
|
||||
five, five
|
||||
)
|
||||
assert_equal(Bool(eq), True)
|
||||
|
||||
var gt = __mlir_op.`index.cmp`[
|
||||
pred=__mlir_attr.`#index.cmp_predicate<sgt>`
|
||||
](five, ten)
|
||||
assert_equal(Bool(gt), False)
|
||||
|
||||
var ne = __mlir_op.`index.cmp`[pred=__mlir_attr.`#index.cmp_predicate<ne>`](
|
||||
five, ten
|
||||
)
|
||||
assert_equal(Bool(ne), True)
|
||||
|
||||
|
||||
def test_index_constant() raises:
|
||||
"""Index dialect: index.constant operation."""
|
||||
var c = __mlir_op.`index.constant`[value=__mlir_attr.`99 : index`]()
|
||||
assert_equal(Int(mlir_value=c), 99)
|
||||
|
||||
|
||||
# --- __mlir_op: pop dialect ---
|
||||
|
||||
|
||||
def test_pop_bool_ops() raises:
|
||||
"""Pop dialect: xor, and, or on i1."""
|
||||
var t: __mlir_type.i1 = __mlir_attr.true
|
||||
var f: __mlir_type.i1 = __mlir_attr.false
|
||||
|
||||
# NOT via XOR with true
|
||||
var not_t = __mlir_op.`pop.xor`(t, __mlir_attr.true)
|
||||
assert_equal(Bool(not_t), False)
|
||||
|
||||
var not_f = __mlir_op.`pop.xor`(f, __mlir_attr.true)
|
||||
assert_equal(Bool(not_f), True)
|
||||
|
||||
# AND
|
||||
var t_and_f = __mlir_op.`pop.and`(t, f)
|
||||
assert_equal(Bool(t_and_f), False)
|
||||
|
||||
var t_and_t = __mlir_op.`pop.and`(t, t)
|
||||
assert_equal(Bool(t_and_t), True)
|
||||
|
||||
# OR
|
||||
var t_or_f = __mlir_op.`pop.or`(t, f)
|
||||
assert_equal(Bool(t_or_f), True)
|
||||
|
||||
var f_or_f = __mlir_op.`pop.or`(f, f)
|
||||
assert_equal(Bool(f_or_f), False)
|
||||
|
||||
|
||||
def test_pop_cast_roundtrip() raises:
|
||||
"""Pop dialect: cast_from_builtin and cast_to_builtin roundtrip."""
|
||||
var idx: __mlir_type.index = __mlir_attr.`42 : index`
|
||||
|
||||
# index → !kgen.scalar<index>
|
||||
var pop_val = __mlir_op.`pop.cast_from_builtin`[
|
||||
_type=__mlir_type.`!kgen.scalar<index>`
|
||||
](idx)
|
||||
|
||||
# !kgen.scalar<index> → index
|
||||
var back = __mlir_op.`pop.cast_to_builtin`[_type=__mlir_type.index](pop_val)
|
||||
|
||||
assert_equal(Int(mlir_value=back), 42)
|
||||
|
||||
|
||||
def test_pop_simd_splat() raises:
|
||||
"""Pop dialect: splat a scalar to a SIMD vector, extract element."""
|
||||
# Create a scalar Float32
|
||||
var idx: __mlir_type.index = __mlir_attr.`3 : index`
|
||||
var pop_idx = __mlir_op.`pop.cast_from_builtin`[
|
||||
_type=__mlir_type.`!kgen.scalar<index>`
|
||||
](idx)
|
||||
var scalar_f32 = __mlir_op.`pop.cast`[
|
||||
_type=__mlir_type.`!kgen.scalar<f32>`
|
||||
](pop_idx)
|
||||
|
||||
# Splat to 4-wide SIMD
|
||||
var vec = __mlir_op.`pop.simd.splat`[
|
||||
_type=__mlir_type.`!kgen.simd<4, f32>`
|
||||
](scalar_f32)
|
||||
|
||||
# Extract element 0 back out
|
||||
var elem = __mlir_op.`pop.simd.extractelement`(
|
||||
vec,
|
||||
__mlir_attr.`0 : index`,
|
||||
)
|
||||
|
||||
# Wrap in SIMD scalar to compare
|
||||
var result = Float32(mlir_value=elem)
|
||||
assert_equal(result, 3.0)
|
||||
|
||||
|
||||
# --- __mlir_op: explicit _type ---
|
||||
|
||||
|
||||
def test_explicit_type_attr() raises:
|
||||
"""The _type attribute specifies result type when inference fails."""
|
||||
var x: __mlir_type.index = __mlir_attr.`255 : index`
|
||||
var casted = __mlir_op.`index.castu`[_type=__mlir_type.i1](x)
|
||||
# 255 truncated to i1 = true (lowest bit is 1)
|
||||
assert_equal(Bool(casted), True)
|
||||
|
||||
|
||||
# --- Wrapper struct pattern ---
|
||||
|
||||
|
||||
struct MiniInt(Writable):
|
||||
"""Minimal wrapper struct demonstrating the inline MLIR pattern."""
|
||||
|
||||
var _mlir_value: __mlir_type.index
|
||||
|
||||
def __init__(out self):
|
||||
self._mlir_value = __mlir_attr.`0 : index`
|
||||
|
||||
def __init__(out self, *, mlir_value: __mlir_type.index):
|
||||
self._mlir_value = mlir_value
|
||||
|
||||
@implicit
|
||||
def __init__(out self, value: Int):
|
||||
self._mlir_value = value.__mlir_index__()
|
||||
|
||||
def __add__(self, rhs: Self) -> Self:
|
||||
return Self(
|
||||
mlir_value=__mlir_op.`index.add`(self._mlir_value, rhs._mlir_value)
|
||||
)
|
||||
|
||||
def __sub__(self, rhs: Self) -> Self:
|
||||
return Self(
|
||||
mlir_value=__mlir_op.`index.sub`(self._mlir_value, rhs._mlir_value)
|
||||
)
|
||||
|
||||
def __mul__(self, rhs: Self) -> Self:
|
||||
return Self(
|
||||
mlir_value=__mlir_op.`index.mul`(self._mlir_value, rhs._mlir_value)
|
||||
)
|
||||
|
||||
def __eq__(self, rhs: Self) -> Bool:
|
||||
return __mlir_op.`index.cmp`[
|
||||
pred=__mlir_attr.`#index.cmp_predicate<eq>`
|
||||
](self._mlir_value, rhs._mlir_value)
|
||||
|
||||
def __lt__(self, rhs: Self) -> Bool:
|
||||
return __mlir_op.`index.cmp`[
|
||||
pred=__mlir_attr.`#index.cmp_predicate<slt>`
|
||||
](self._mlir_value, rhs._mlir_value)
|
||||
|
||||
def to_int(self) -> Int:
|
||||
return Int(mlir_value=self._mlir_value)
|
||||
|
||||
def write_to(self, mut writer: Some[Writer]):
|
||||
writer.write(self.to_int())
|
||||
|
||||
|
||||
def test_wrapper_struct_arithmetic() raises:
|
||||
"""Wrapper struct: add, sub, mul through MLIR ops."""
|
||||
var a = MiniInt(10)
|
||||
var b = MiniInt(3)
|
||||
assert_equal((a + b).to_int(), 13)
|
||||
assert_equal((a - b).to_int(), 7)
|
||||
assert_equal((a * b).to_int(), 30)
|
||||
|
||||
|
||||
def test_wrapper_struct_comparison() raises:
|
||||
"""Wrapper struct: eq and lt through MLIR cmp."""
|
||||
var a = MiniInt(5)
|
||||
var b = MiniInt(10)
|
||||
assert_equal(a == a, True)
|
||||
assert_equal(a == b, False)
|
||||
assert_equal(a < b, True)
|
||||
assert_equal(b < a, False)
|
||||
|
||||
|
||||
def test_wrapper_struct_write() raises:
|
||||
"""Wrapper struct: Writable conformance through MLIR value."""
|
||||
var x = MiniInt(42)
|
||||
assert_equal(String(x), "42")
|
||||
|
||||
|
||||
# --- Multiple operations chained ---
|
||||
|
||||
|
||||
def test_chained_ops() raises:
|
||||
"""Multiple MLIR ops chained: (a + b) * c."""
|
||||
var a: __mlir_type.index = __mlir_attr.`2 : index`
|
||||
var b: __mlir_type.index = __mlir_attr.`3 : index`
|
||||
var c: __mlir_type.index = __mlir_attr.`7 : index`
|
||||
|
||||
var sum = __mlir_op.`index.add`(a, b)
|
||||
var product = __mlir_op.`index.mul`(sum, c)
|
||||
assert_equal(Int(mlir_value=product), 35) # (2+3)*7
|
||||
|
||||
|
||||
def test_conditional_on_mlir_cmp() raises:
|
||||
"""MLIR comparison result used in Mojo control flow."""
|
||||
var x: __mlir_type.index = __mlir_attr.`42 : index`
|
||||
var threshold: __mlir_type.index = __mlir_attr.`10 : index`
|
||||
|
||||
var above = __mlir_op.`index.cmp`[
|
||||
pred=__mlir_attr.`#index.cmp_predicate<sgt>`
|
||||
](x, threshold)
|
||||
|
||||
var label = "big" if Bool(above) else "small"
|
||||
assert_equal(label, "big")
|
||||
|
||||
|
||||
def sum_to(end: Int) -> Int:
|
||||
"""Mojo while loop with MLIR operations for arithmetic and comparison."""
|
||||
var acc: __mlir_type.index = __mlir_attr.`0 : index`
|
||||
var i: __mlir_type.index = __mlir_attr.`0 : index`
|
||||
var one: __mlir_type.index = __mlir_attr.`1 : index`
|
||||
|
||||
# end.__mlir_index__() converts Int to raw __mlir_type.index
|
||||
while Bool(
|
||||
__mlir_op.`index.cmp`[pred=__mlir_attr.`#index.cmp_predicate<slt>`](
|
||||
i, end.__mlir_index__()
|
||||
)
|
||||
):
|
||||
acc = __mlir_op.`index.add`(acc, i)
|
||||
i = __mlir_op.`index.add`(i, one)
|
||||
|
||||
return Int(mlir_value=acc)
|
||||
|
||||
|
||||
def test_mlir_in_mojo_loop() raises:
|
||||
"""MLIR operations used in a Mojo while loop to sum integers."""
|
||||
assert_equal(sum_to(10), 45) # 0+1+2+...+9 = 45
|
||||
assert_equal(sum_to(0), 0)
|
||||
assert_equal(sum_to(1), 0)
|
||||
assert_equal(sum_to(5), 10) # 0+1+2+3+4 = 10
|
||||
|
||||
|
||||
# --- Additional examples added for practical use ---
|
||||
|
||||
|
||||
def test_mlir_types_in_action() raises:
|
||||
"""Types in action: declare, assign, convert back."""
|
||||
var flag: __mlir_type.i1 = __mlir_attr.true
|
||||
var count: __mlir_type.index = __mlir_attr.`0 : index`
|
||||
assert_equal(Bool(flag), True)
|
||||
assert_equal(Int(mlir_value=count), 0)
|
||||
|
||||
|
||||
def test_circle_area_approx() raises:
|
||||
"""MLIR attrs as constants in a computation."""
|
||||
|
||||
def circle_area_approx(radius: Int) -> Int:
|
||||
var r = radius.__mlir_index__()
|
||||
var r_squared = __mlir_op.`index.mul`(r, r)
|
||||
var pi: __mlir_type.index = __mlir_attr.`3 : index`
|
||||
var area = __mlir_op.`index.mul`(pi, r_squared)
|
||||
return Int(mlir_value=area)
|
||||
|
||||
assert_equal(circle_area_approx(5), 75)
|
||||
assert_equal(circle_area_approx(10), 300)
|
||||
assert_equal(circle_area_approx(0), 0)
|
||||
|
||||
|
||||
def test_clamp() raises:
|
||||
"""Comparisons with pop.select to clamp a value."""
|
||||
|
||||
def clamp(val: Int, low: Int, high: Int) -> Int:
|
||||
var v = val.__mlir_index__()
|
||||
var lo = low.__mlir_index__()
|
||||
var hi = high.__mlir_index__()
|
||||
# index.cmp returns i1, but pop.select needs a !kgen.scalar<bool>.
|
||||
var too_low = __mlir_op.`pop.cast_from_builtin`[
|
||||
_type=__mlir_type.`!kgen.scalar<bool>`
|
||||
](
|
||||
__mlir_op.`index.cmp`[pred=__mlir_attr.`#index.cmp_predicate<slt>`](
|
||||
v, lo
|
||||
)
|
||||
)
|
||||
var result = __mlir_op.`pop.select`(too_low, lo, v)
|
||||
var too_high = __mlir_op.`pop.cast_from_builtin`[
|
||||
_type=__mlir_type.`!kgen.scalar<bool>`
|
||||
](
|
||||
__mlir_op.`index.cmp`[pred=__mlir_attr.`#index.cmp_predicate<sgt>`](
|
||||
result, hi
|
||||
)
|
||||
)
|
||||
result = __mlir_op.`pop.select`(too_high, hi, result)
|
||||
return Int(mlir_value=result)
|
||||
|
||||
assert_equal(clamp(15, 0, 10), 10)
|
||||
assert_equal(clamp(-5, 0, 10), 0)
|
||||
assert_equal(clamp(7, 0, 10), 7)
|
||||
assert_equal(clamp(0, 0, 10), 0)
|
||||
assert_equal(clamp(10, 0, 10), 10)
|
||||
|
||||
|
||||
struct Counter:
|
||||
"""Wrapper struct from doc page: counter backed by raw MLIR index."""
|
||||
|
||||
var _mlir_value: __mlir_type.index
|
||||
|
||||
def __init__(out self):
|
||||
self._mlir_value = __mlir_attr.`0 : index`
|
||||
|
||||
def __init__(out self, *, mlir_value: __mlir_type.index):
|
||||
self._mlir_value = mlir_value
|
||||
|
||||
def increment(mut self):
|
||||
var one: __mlir_type.index = __mlir_attr.`1 : index`
|
||||
self._mlir_value = __mlir_op.`index.add`(self._mlir_value, one)
|
||||
|
||||
def __add__(self, rhs: Counter) -> Counter:
|
||||
return Counter(
|
||||
mlir_value=__mlir_op.`index.add`(self._mlir_value, rhs._mlir_value)
|
||||
)
|
||||
|
||||
def value(self) -> Int:
|
||||
return Int(mlir_value=self._mlir_value)
|
||||
|
||||
|
||||
def test_counter_increment() raises:
|
||||
"""Counter wrapper struct: increment and read back."""
|
||||
var c = Counter()
|
||||
assert_equal(c.value(), 0)
|
||||
c.increment()
|
||||
c.increment()
|
||||
c.increment()
|
||||
assert_equal(c.value(), 3)
|
||||
|
||||
|
||||
def test_counter_add() raises:
|
||||
"""Counter with __add__: operations as methods pattern."""
|
||||
var a = Counter()
|
||||
a.increment() # 1
|
||||
a.increment() # 2
|
||||
var b = Counter()
|
||||
b.increment() # 1
|
||||
var c = a + b # 2 + 1 = 3
|
||||
assert_equal(c.value(), 3)
|
||||
|
||||
|
||||
def main() raises:
|
||||
test_hello_mlir()
|
||||
test_mlir_type_dot_syntax()
|
||||
test_mlir_type_backtick_syntax()
|
||||
test_mlir_attr_bool()
|
||||
test_mlir_attr_typed_constants()
|
||||
test_index_arithmetic()
|
||||
test_index_bitwise()
|
||||
test_index_comparisons()
|
||||
test_index_constant()
|
||||
test_pop_bool_ops()
|
||||
test_pop_cast_roundtrip()
|
||||
test_pop_simd_splat()
|
||||
test_explicit_type_attr()
|
||||
test_wrapper_struct_arithmetic()
|
||||
test_wrapper_struct_comparison()
|
||||
test_wrapper_struct_write()
|
||||
test_chained_ops()
|
||||
test_conditional_on_mlir_cmp()
|
||||
test_mlir_in_mojo_loop()
|
||||
test_mlir_types_in_action()
|
||||
test_circle_area_approx()
|
||||
test_clamp()
|
||||
test_counter_increment()
|
||||
test_counter_add()
|
||||
@@ -0,0 +1,147 @@
|
||||
# ===----------------------------------------------------------------------=== #
|
||||
# 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 keywords.mdx code examples.
|
||||
# Skip: CountingTool.get (intentional immutable-self error),
|
||||
# make_point with both `out` and `->` (intentional signature
|
||||
# error), bare identifier name lists (not standalone code).
|
||||
from std.testing import assert_equal
|
||||
|
||||
|
||||
# --- Regular identifiers ---
|
||||
|
||||
|
||||
def test_regular_identifiers() raises:
|
||||
var foo = 1
|
||||
var _private = 2
|
||||
var MyStruct = 3
|
||||
var basic_value = 4
|
||||
assert_equal(foo, 1)
|
||||
assert_equal(_private, 2)
|
||||
assert_equal(MyStruct, 3)
|
||||
assert_equal(basic_value, 4)
|
||||
|
||||
|
||||
# --- Escaped identifiers ---
|
||||
|
||||
|
||||
def test_escaped_identifiers() raises:
|
||||
var `struct` = 10 # Use a keyword as a name
|
||||
var `日本語の変数` = 20 # Non-ASCII identifier
|
||||
var `my value` = 30 # Spaces in a name
|
||||
assert_equal(`struct`, 10)
|
||||
assert_equal(`日本語の変数`, 20)
|
||||
assert_equal(`my value`, 30)
|
||||
|
||||
|
||||
# --- Identifiers are case-sensitive ---
|
||||
|
||||
|
||||
def test_case_sensitivity() raises:
|
||||
var MyStruct = 1
|
||||
var mystruct = 2
|
||||
assert_equal(MyStruct, 1)
|
||||
assert_equal(mystruct, 2)
|
||||
|
||||
|
||||
# --- Struct with `out self`, `mut self`, and `var` field ---
|
||||
# `get()` can't be tested as it intentionally errors
|
||||
|
||||
|
||||
struct CountingTool:
|
||||
var value: Int
|
||||
|
||||
def __init__(out self): # out: self is the return value
|
||||
self.value = 0
|
||||
|
||||
def increment(mut self): # mut: modifies self in place
|
||||
self.value += 1
|
||||
|
||||
|
||||
def test_counting_tool() raises:
|
||||
var t = CountingTool()
|
||||
assert_equal(t.value, 0)
|
||||
t.increment()
|
||||
assert_equal(t.value, 1)
|
||||
t.increment()
|
||||
assert_equal(t.value, 2)
|
||||
|
||||
|
||||
# --- `var` creates a scoped mutable variable;
|
||||
# `ref` creates a scoped reference binding ---
|
||||
|
||||
|
||||
def test_var_and_ref() raises:
|
||||
var count = 0
|
||||
count += 1
|
||||
assert_equal(count, 1)
|
||||
|
||||
var data: List[Int] = [1, 2, 3]
|
||||
ref view = data
|
||||
assert_equal(view[0], 1)
|
||||
assert_equal(view[2], 3)
|
||||
|
||||
|
||||
# --- `out` convention: out arg replaces explicit return type ---
|
||||
|
||||
|
||||
struct Point(Copyable, Movable):
|
||||
var x: Int
|
||||
var y: Int
|
||||
|
||||
def __init__(out self, x: Int, y: Int):
|
||||
self.x = x
|
||||
self.y = y
|
||||
|
||||
|
||||
def make_point(out result: Point):
|
||||
result = Point(0, 0)
|
||||
|
||||
|
||||
def test_make_point() raises:
|
||||
var p = make_point()
|
||||
assert_equal(p.x, 0)
|
||||
assert_equal(p.y, 0)
|
||||
|
||||
|
||||
# --- `raises` clause in signatures ---
|
||||
|
||||
|
||||
def validate(value: Int) raises:
|
||||
if value < 0:
|
||||
raise Error("must be non-negative")
|
||||
|
||||
|
||||
def test_validate_ok() raises:
|
||||
validate(5)
|
||||
validate(0)
|
||||
|
||||
|
||||
def test_validate_raises() raises:
|
||||
var raised = False
|
||||
try:
|
||||
validate(-1)
|
||||
except e:
|
||||
raised = True
|
||||
assert_equal(raised, True)
|
||||
|
||||
|
||||
def main() raises:
|
||||
test_regular_identifiers()
|
||||
test_escaped_identifiers()
|
||||
test_case_sensitivity()
|
||||
test_counting_tool()
|
||||
test_var_and_ref()
|
||||
test_make_point()
|
||||
test_validate_ok()
|
||||
test_validate_raises()
|
||||
@@ -0,0 +1,546 @@
|
||||
# ===----------------------------------------------------------------------=== #
|
||||
# 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-expressions.mdx code examples.
|
||||
#
|
||||
# Not tested (rejected forms have no runnable behavior to assert). Each is
|
||||
# documented in the page as a paraphrased error gist; the compiler tests that
|
||||
# pin the exact diagnostics live in
|
||||
# KGEN/test/mojo-parser/exprs/expressions_errors.mojo:
|
||||
# - `lambda x, y: x + y` (unparenthesized arguments)
|
||||
# - `lambda (x) {} -> Int: x` (untyped argument)
|
||||
# - `lambda: 5` and `lambda (x: Int) {}: x + 1` (non-`None` body under an
|
||||
# elided return type)
|
||||
# - `lambda (x: Int) {} -> Int: x + z` (free variable under explicit `{}`)
|
||||
# - `lambda (x: Int) {imm list} -> None: list.append(x)` (mutation through an
|
||||
# `imm` capture)
|
||||
# - a lambda closure in a `comptime` initializer, a type parameter, or a
|
||||
# default parameter
|
||||
# - a lambda closure, capturing or parametric, assigned where a `thin`
|
||||
# function pointer is required
|
||||
from std.testing import assert_equal, assert_raises
|
||||
|
||||
# --- Helpers used across the thin-pointer and parameter tests ---
|
||||
|
||||
|
||||
def apply_thin(f: def(x: Int) thin -> Int, arg: Int) -> Int:
|
||||
return f(arg)
|
||||
|
||||
|
||||
def apply_raising(f: def(x: Int) raises thin -> Int, arg: Int) raises -> Int:
|
||||
return f(arg)
|
||||
|
||||
|
||||
def call_with[f: def(x: Int) thin -> Int]() -> Int:
|
||||
return f(10)
|
||||
|
||||
|
||||
def call_with_default[
|
||||
f: def(x: Int) thin -> Int = lambda (x: Int) -> Int: x + 5
|
||||
]() -> Int:
|
||||
return f(10)
|
||||
|
||||
|
||||
def make_adder() -> def(x: Int) thin -> Int:
|
||||
return lambda (x: Int) -> Int: x + 10
|
||||
|
||||
|
||||
def with_default_arg(
|
||||
x: Int, cb: def(x: Int) thin -> Int = lambda (x: Int) -> Int: x + 1
|
||||
) -> Int:
|
||||
return cb(x)
|
||||
|
||||
|
||||
def take_two(*fs: def(x: Int) thin -> Int) -> Int:
|
||||
return fs[0](1) + fs[1](1)
|
||||
|
||||
|
||||
def total_as_ints[T: Intable & Copyable](args: List[T]) -> Int:
|
||||
var to_int: def(v: T) thin -> Int = lambda (v: T) -> Int: Int(v)
|
||||
var total = 0
|
||||
for ref a in args:
|
||||
total += to_int(a)
|
||||
return total
|
||||
|
||||
|
||||
# `T` is inferred from the lambda passed for `f`, so both a thin lambda
|
||||
# and a lambda closure bind here.
|
||||
def call_inferred[T: def(x: Int) -> Int, //](f: T, arg: Int) -> Int:
|
||||
return f(arg)
|
||||
|
||||
|
||||
# `R` appears only inside the function-trait bound on `F`, so it is solved
|
||||
# from the lambda's return type.
|
||||
def call_for_result[R: AnyType, F: def(x: Int) -> R, //](f: F, arg: Int) -> R:
|
||||
return f(arg)
|
||||
|
||||
|
||||
# --- Syntax: the fully explicit form ---
|
||||
|
||||
|
||||
def test_explicit_form() raises:
|
||||
var f = lambda (x: Int) {} -> Int: x + 1
|
||||
assert_equal(f(4), 5)
|
||||
|
||||
|
||||
def test_conventions() raises:
|
||||
var read_arg = lambda (x: Int) {} -> Int: x + 1
|
||||
# AKA: var read_arg = lambda (imm x: Int) {} -> Int: x + 1
|
||||
var own_arg = lambda (var x: Int) {} -> Int: x + 1
|
||||
var mut_arg = lambda (mut x: Int) {}: x.__iadd__(1)
|
||||
|
||||
var list: List[Int] = [1, 2, 3]
|
||||
mut_arg(list[0])
|
||||
assert_equal(list, [2, 2, 3])
|
||||
assert_equal(read_arg(1), 2)
|
||||
assert_equal(own_arg(1), 2)
|
||||
|
||||
|
||||
def test_parameterized() raises:
|
||||
var inc = lambda [T: Intable](x: T) -> Int: Int(x) + 1
|
||||
assert_equal(inc[Float64](3.5), 4)
|
||||
assert_equal(inc[Int](3), 4)
|
||||
assert_equal(inc(3.5), 4)
|
||||
|
||||
|
||||
def test_concrete() raises:
|
||||
var hello = lambda (x: String) {} -> String: "Hello, " + x
|
||||
assert_equal(hello("World"), "Hello, World")
|
||||
assert_equal(hello("Mojo"), "Hello, Mojo")
|
||||
|
||||
|
||||
def test_no_arguments() raises:
|
||||
var no_args = lambda -> Int: 42
|
||||
assert_equal(no_args(), 42)
|
||||
|
||||
|
||||
def test_base_capture() raises:
|
||||
var z = 10
|
||||
var f = lambda (x: Int) -> Int: x + z # `z` is captured
|
||||
assert_equal(f(5), 15)
|
||||
|
||||
|
||||
def test_mut_capture() raises:
|
||||
var list: List[Int] = [1, 2, 3]
|
||||
var f = lambda (x: Int) {mut list}: list.append(x)
|
||||
f(10)
|
||||
assert_equal(list, [1, 2, 3, 10])
|
||||
|
||||
|
||||
def test_parameter_capture() raises:
|
||||
# N is lambda-owned, bound at each call
|
||||
var f = lambda [N: Int](x: Int) {} -> Int: x + N
|
||||
assert_equal(f[5](3), 8)
|
||||
|
||||
|
||||
def test_thin_parameter_enclosing_scope() raises:
|
||||
assert_equal(total_as_ints([1.5, 2.5, 3.9]), 6)
|
||||
|
||||
|
||||
# --- Elision: the capture list may be omitted ---
|
||||
|
||||
|
||||
def test_elided_capture_list() raises:
|
||||
var f = lambda (x: Int) -> Int: x * 2
|
||||
assert_equal(f(4), 8)
|
||||
|
||||
|
||||
# --- Elision: an omitted return type defaults to `None` ---
|
||||
|
||||
|
||||
def test_elided_return_type() raises:
|
||||
var list: List[Int] = [1]
|
||||
var push = lambda (x: Int) {mut list}: list.append(x)
|
||||
push(2)
|
||||
push(3)
|
||||
assert_equal(len(list), 3)
|
||||
assert_equal(list[2], 3)
|
||||
|
||||
|
||||
# --- Elision: the bare form takes no arguments ---
|
||||
|
||||
|
||||
def test_bare_lambda() raises:
|
||||
var count = 0
|
||||
var bump = lambda {mut count}: count.__iadd__(1)
|
||||
bump()
|
||||
bump()
|
||||
assert_equal(count, 2)
|
||||
|
||||
|
||||
# --- Captures: an omitted capture list captures free variables by `imm` ---
|
||||
|
||||
|
||||
def test_omitted_capture_list_is_imm() raises:
|
||||
var z = 3
|
||||
var f = lambda (x: Int) -> Int: x + z
|
||||
assert_equal(f(1), 4)
|
||||
# An `imm` capture holds a reference, so the lambda observes the
|
||||
# current value at each call, not a snapshot.
|
||||
z = 30
|
||||
assert_equal(f(1), 31)
|
||||
|
||||
|
||||
# --- Captures: a named capture ---
|
||||
|
||||
|
||||
def test_named_capture() raises:
|
||||
var z = 3
|
||||
var f = lambda (x: Int) {imm z} -> Int: x + z
|
||||
assert_equal(f(1), 4)
|
||||
|
||||
|
||||
# --- Captures: a `mut` capture-all mutates the outer value ---
|
||||
|
||||
|
||||
def test_mut_capture_all() raises:
|
||||
var total = 0
|
||||
var add = lambda (x: Int) {mut}: total.__iadd__(x)
|
||||
add(5)
|
||||
add(7)
|
||||
assert_equal(total, 12)
|
||||
|
||||
|
||||
# --- Captures: a `var` capture takes an owned copy (a snapshot) ---
|
||||
|
||||
|
||||
def test_var_capture_snapshot() raises:
|
||||
var z = 3
|
||||
var f = lambda (x: Int) {var z} -> Int: x + z
|
||||
assert_equal(f(1), 4)
|
||||
z = 30
|
||||
assert_equal(z, 30)
|
||||
# The copy was taken when the lambda was created.
|
||||
assert_equal(f(1), 4)
|
||||
|
||||
|
||||
# --- Captures: mixed conventions in one list ---
|
||||
|
||||
|
||||
def test_mixed_conventions() raises:
|
||||
var counts: List = [0]
|
||||
var step = 2
|
||||
var bump = lambda (x: Int) {mut counts, imm step}: counts.append(x + step)
|
||||
bump(1)
|
||||
assert_equal(len(counts), 2)
|
||||
assert_equal(counts[1], 3)
|
||||
|
||||
|
||||
# --- Compile-time: a thin lambda binds to a `comptime` ---
|
||||
|
||||
comptime INC = lambda (x: Int) -> Int: x + 1
|
||||
|
||||
|
||||
struct Ops:
|
||||
comptime inc = lambda (x: Int) {} -> Int: x + 1
|
||||
|
||||
|
||||
def test_comptime_bind() raises:
|
||||
comptime local_inc = lambda (x: Int) {} -> Int: x + 1
|
||||
assert_equal(local_inc(1), 2)
|
||||
assert_equal(INC(1), 2)
|
||||
assert_equal(Ops.inc(3), 4)
|
||||
|
||||
|
||||
# --- Compile-time: applying a lambda at comptime folds the result ---
|
||||
|
||||
|
||||
def test_comptime_apply() raises:
|
||||
comptime whole = (lambda (x: Int) {} -> Int: x * 2)(21)
|
||||
assert_equal(whole, 42)
|
||||
|
||||
|
||||
# --- Compile-time: a comptime lambda is one promoted function ---
|
||||
|
||||
|
||||
def test_comptime_reference() raises:
|
||||
comptime dbl = lambda (x: Int) {} -> Int: x * 2
|
||||
comptime compose = lambda (x: Int) {} -> Int: dbl(x) + 1
|
||||
assert_equal(compose(4), 9)
|
||||
|
||||
|
||||
# --- Compile-time: an enclosing parameter folds in and keeps the lambda thin ---
|
||||
|
||||
comptime ADD_GEN[N: Int] = lambda (x: Int) {} -> Int: x + N
|
||||
comptime ADD_LAM = lambda [N: Int](x: Int) {} -> Int: x + N
|
||||
|
||||
|
||||
def add_local[N: Int](v: Int) -> Int:
|
||||
comptime f = lambda (x: Int) {} -> Int: x + N
|
||||
return f(v)
|
||||
|
||||
|
||||
def test_comptime_parameters() raises:
|
||||
assert_equal(ADD_GEN[7](3), 10)
|
||||
assert_equal(ADD_LAM[7](3), 10)
|
||||
assert_equal(add_local[7](3), 10)
|
||||
|
||||
|
||||
# --- Compile-time: a thin lambda binds to a `thin` function-typed parameter ---
|
||||
|
||||
|
||||
def call_with_enclosing[N: Int]() -> Int:
|
||||
return call_with[lambda (x: Int) {} -> Int: x + N]()
|
||||
|
||||
|
||||
def test_thin_fn_typed_parameter() raises:
|
||||
assert_equal(call_with[lambda (x: Int) {} -> Int: x * 2](), 20)
|
||||
# The capture list may be elided and the lambda is still thin.
|
||||
assert_equal(call_with[lambda (x: Int) -> Int: x * 4](), 40)
|
||||
assert_equal(call_with_default(), 15)
|
||||
assert_equal(call_with_enclosing[7](), 17)
|
||||
|
||||
|
||||
# --- Compile-time: the parameter can be on a struct, including its default ---
|
||||
|
||||
|
||||
struct Scaled[f: def(x: Int) thin -> Int = lambda (x: Int) {} -> Int: x * 3]:
|
||||
var v: Int
|
||||
|
||||
def __init__(out self, arg: Int):
|
||||
self.v = Self.f(arg)
|
||||
|
||||
|
||||
def test_struct_fn_parameter() raises:
|
||||
assert_equal(Scaled[lambda (x: Int) {} -> Int: x + 1](4).v, 5)
|
||||
assert_equal(Scaled(4).v, 12)
|
||||
|
||||
|
||||
# --- Runtime: a thin lambda works as a `thin` function pointer ---
|
||||
|
||||
|
||||
struct Holder:
|
||||
var cb: def(x: Int) thin -> Int
|
||||
|
||||
def __init__(out self):
|
||||
self.cb = lambda (x: Int) -> Int: x * 2
|
||||
|
||||
|
||||
def thin_with_enclosing_param[N: Int]() -> Int:
|
||||
var f: def(x: Int) thin -> Int = lambda (x: Int) -> Int: x + N
|
||||
return f(1)
|
||||
|
||||
|
||||
struct SelfParamDecay[P: Int]:
|
||||
var v: Int
|
||||
|
||||
def __init__(out self):
|
||||
var f: def(x: Int) thin -> Int = lambda (x: Int) -> Int: x + Self.P
|
||||
self.v = f(1)
|
||||
|
||||
|
||||
def test_thin_pointer_typed_var() raises:
|
||||
var t: def(x: Int) thin -> Int = lambda (x: Int) -> Int: x + 1
|
||||
assert_equal(t(1), 2)
|
||||
# The variable holds a function value, so it is rebindable.
|
||||
t = lambda (x: Int) -> Int: x * 3
|
||||
assert_equal(t(2), 6)
|
||||
# An explicit `{}` is thin too, and works the same way.
|
||||
t = lambda (x: Int) {} -> Int: x + 7
|
||||
assert_equal(t(2), 9)
|
||||
|
||||
|
||||
def test_thin_pointer_untyped_var() raises:
|
||||
var u = lambda (x: Int) -> Int: x + 100
|
||||
assert_equal(u(1), 101)
|
||||
u = lambda (x: Int) -> Int: x + 1000
|
||||
assert_equal(u(1), 1001)
|
||||
|
||||
|
||||
def test_thin_pointer_return_value() raises:
|
||||
assert_equal(make_adder()(5), 15)
|
||||
|
||||
|
||||
def test_thin_pointer_argument() raises:
|
||||
assert_equal(apply_thin(lambda (x: Int) -> Int: x - 1, 4), 3)
|
||||
|
||||
|
||||
def test_thin_pointer_default_argument() raises:
|
||||
assert_equal(with_default_arg(4), 5)
|
||||
assert_equal(with_default_arg(4, lambda (x: Int) -> Int: x * 10), 40)
|
||||
|
||||
|
||||
def test_thin_pointer_struct_field() raises:
|
||||
var h = Holder()
|
||||
assert_equal(h.cb(3), 6)
|
||||
h.cb = lambda (x: Int) -> Int: x + 30
|
||||
assert_equal(h.cb(3), 33)
|
||||
|
||||
|
||||
def test_thin_pointer_enclosing_parameter() raises:
|
||||
assert_equal(thin_with_enclosing_param[5](), 6)
|
||||
assert_equal(SelfParamDecay[7]().v, 8)
|
||||
|
||||
|
||||
def test_thin_pointer_variadic_pack() raises:
|
||||
assert_equal(
|
||||
take_two(lambda (x: Int) -> Int: x + 1, lambda (x: Int) -> Int: x * 2),
|
||||
4,
|
||||
)
|
||||
|
||||
|
||||
# --- Effects: a raising lambda fills a `raises thin` parameter ---
|
||||
|
||||
|
||||
def test_raising_lambda() raises:
|
||||
assert_equal(apply_raising(lambda (x: Int) raises -> Int: x + 1, 2), 3)
|
||||
|
||||
|
||||
def checked(x: Int) raises -> Int:
|
||||
if x < 0:
|
||||
raise Error("negative")
|
||||
return x
|
||||
|
||||
|
||||
def test_raising_lambda_actually_raises() raises:
|
||||
var f = lambda (x: Int) raises -> Int: checked(x) + 1
|
||||
assert_equal(f(1), 2)
|
||||
with assert_raises(contains="negative"):
|
||||
_ = f(-1)
|
||||
|
||||
|
||||
# --- C ABI: a thin lambda fills a C-ABI function pointer ---
|
||||
|
||||
|
||||
def test_c_abi_callback() raises:
|
||||
# `abi("C")` goes on the lambda; the variable's type is inferred.
|
||||
var fp = lambda (a: Int32, b: Int32) abi("C") -> Int32: a + b
|
||||
assert_equal(fp(1, 2), 3)
|
||||
|
||||
# With explicit typing, the annotation must carry `abi("C")` as well.
|
||||
var typed: def(Int32, Int32) thin abi("C") -> Int32 = (
|
||||
lambda (a: Int32, b: Int32) abi("C") -> Int32: a * b
|
||||
)
|
||||
assert_equal(typed(3, 4), 12)
|
||||
|
||||
|
||||
# --- Parameters: a lambda can declare its own compile-time parameters ---
|
||||
|
||||
|
||||
def test_parametric_lambda() raises:
|
||||
var pf = lambda [N: Int](x: Int) {} -> Int: x + N
|
||||
assert_equal(pf[5](3), 8)
|
||||
assert_equal(pf[10](3), 13)
|
||||
|
||||
|
||||
def test_parametric_lambda_nested() raises:
|
||||
var pn = lambda [N: Int](x: Int) {} -> Int: (
|
||||
lambda (y: Int) {} -> Int: y + N
|
||||
)(x)
|
||||
assert_equal(pn[10](3), 13)
|
||||
|
||||
|
||||
# --- Arguments: variadic forms ---
|
||||
|
||||
|
||||
def test_variadic_args() raises:
|
||||
var va = lambda (*args: Int) {} -> Int: len(args)
|
||||
assert_equal(va(10, 20, 30), 3)
|
||||
|
||||
|
||||
def test_variadic_kwargs() raises:
|
||||
var kw = lambda (var **kwargs: Int) {} -> Int: len(kwargs)
|
||||
assert_equal(kw(a=1, b=2), 2)
|
||||
|
||||
|
||||
def test_variadic_both() raises:
|
||||
var both = lambda (*args: Int, var **kwargs: Int) {} -> Int: len(
|
||||
args
|
||||
) + len(kwargs)
|
||||
assert_equal(both(1, 2, a=3), 3)
|
||||
|
||||
|
||||
def test_variadic_thin_pointer() raises:
|
||||
var vd: def(* args: Int) thin -> Int = lambda (*args: Int) -> Int: len(args)
|
||||
assert_equal(vd(1, 2, 3), 3)
|
||||
|
||||
|
||||
# --- Arguments: argument conventions ---
|
||||
|
||||
|
||||
def test_argument_conventions() raises:
|
||||
var imm_arg = lambda (imm x: Int) {} -> Int: x + 1
|
||||
assert_equal(imm_arg(1), 2)
|
||||
var var_arg = lambda (var x: Int) {} -> Int: x + 1
|
||||
assert_equal(var_arg(1), 2)
|
||||
var mut_arg = lambda (mut x: Int) {}: x.__iadd__(1)
|
||||
var v = 1
|
||||
mut_arg(v)
|
||||
assert_equal(v, 2)
|
||||
|
||||
|
||||
# --- Nesting: a lambda body can contain another lambda ---
|
||||
|
||||
|
||||
def test_nested_lambda() raises:
|
||||
var f = lambda (x: Int) {} -> Int: (lambda (y: Int) {imm x} -> Int: y + x)(
|
||||
3
|
||||
)
|
||||
assert_equal(f(6), 9)
|
||||
|
||||
|
||||
# --- Inference: a lambda binds an inferred function-typed parameter ---
|
||||
|
||||
|
||||
def test_inferred_parameter_type() raises:
|
||||
assert_equal(call_inferred(lambda (x: Int) {} -> Int: x + 1, 4), 5)
|
||||
var z = 10
|
||||
# Inference works for a lambda closure too.
|
||||
assert_equal(call_inferred(lambda (x: Int) {mut} -> Int: x + z, 5), 15)
|
||||
assert_equal(call_for_result(lambda (x: Int) {} -> Int: x * 2, 6), 12)
|
||||
|
||||
|
||||
def main() raises:
|
||||
test_explicit_form()
|
||||
test_conventions()
|
||||
test_parameterized()
|
||||
test_no_arguments()
|
||||
test_concrete()
|
||||
test_base_capture()
|
||||
test_mut_capture()
|
||||
test_parameter_capture()
|
||||
test_thin_parameter_enclosing_scope()
|
||||
test_elided_capture_list()
|
||||
test_elided_return_type()
|
||||
test_bare_lambda()
|
||||
test_omitted_capture_list_is_imm()
|
||||
test_named_capture()
|
||||
test_mut_capture_all()
|
||||
test_var_capture_snapshot()
|
||||
test_mixed_conventions()
|
||||
test_comptime_bind()
|
||||
test_comptime_apply()
|
||||
test_comptime_reference()
|
||||
test_comptime_parameters()
|
||||
test_thin_fn_typed_parameter()
|
||||
test_struct_fn_parameter()
|
||||
test_thin_pointer_typed_var()
|
||||
test_thin_pointer_untyped_var()
|
||||
test_thin_pointer_return_value()
|
||||
test_thin_pointer_argument()
|
||||
test_thin_pointer_default_argument()
|
||||
test_thin_pointer_struct_field()
|
||||
test_thin_pointer_enclosing_parameter()
|
||||
test_thin_pointer_variadic_pack()
|
||||
test_c_abi_callback()
|
||||
test_raising_lambda()
|
||||
test_raising_lambda_actually_raises()
|
||||
test_parametric_lambda()
|
||||
test_parametric_lambda_nested()
|
||||
test_variadic_args()
|
||||
test_variadic_kwargs()
|
||||
test_variadic_both()
|
||||
test_variadic_thin_pointer()
|
||||
test_argument_conventions()
|
||||
test_nested_lambda()
|
||||
test_inferred_parameter_type()
|
||||
@@ -0,0 +1,238 @@
|
||||
# ===----------------------------------------------------------------------=== #
|
||||
# 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 literals.mdx code examples.
|
||||
# Skip: leading-zero decimal error, empty base-prefix errors,
|
||||
# bad-exponent errors, duplicate `greet()` (signature
|
||||
# collision), Drawable.draw error pair only, discard
|
||||
# pattern `_, y = ...` (tuple-destructuring syntax in
|
||||
# flux).
|
||||
from std.testing import assert_equal
|
||||
from std.math import sqrt
|
||||
|
||||
|
||||
# --- Integer bases ---
|
||||
|
||||
|
||||
def test_integer_bases() raises:
|
||||
assert_equal(0xFF, 255)
|
||||
assert_equal(0o52, 42)
|
||||
assert_equal(0b101010, 42)
|
||||
assert_equal(0xFF, 255) # lowercase prefix
|
||||
assert_equal(0o52, 42) # uppercase O
|
||||
assert_equal(0b101010, 42) # uppercase B
|
||||
|
||||
|
||||
# --- Integer underscores ---
|
||||
|
||||
|
||||
def test_integer_underscores() raises:
|
||||
assert_equal(1_000_000, 1000000)
|
||||
var x = 1__000 # cannot test with trailing underscore, kills formatter
|
||||
assert_equal(x, 1000)
|
||||
|
||||
|
||||
# --- Float forms ---
|
||||
|
||||
|
||||
def test_float_forms() raises:
|
||||
assert_equal(1.0, 1.0)
|
||||
assert_equal(0.5, 0.5)
|
||||
assert_equal(2.0, 2.0)
|
||||
assert_equal(2.5e-3, 0.0025)
|
||||
assert_equal(1e10, 1.0e10)
|
||||
assert_equal(1_000.000_5, 1000.0005)
|
||||
|
||||
|
||||
# --- String quote styles ---
|
||||
|
||||
|
||||
def test_string_quotes() raises:
|
||||
assert_equal("Hello", "Hello")
|
||||
var triple = """Multi-line
|
||||
string
|
||||
"""
|
||||
assert_equal(triple, "Multi-line\nstring\n")
|
||||
var triple_single = """Also
|
||||
multi-line"""
|
||||
assert_equal(triple_single, "Also\n multi-line")
|
||||
|
||||
|
||||
# --- Adjacent string concatenation ---
|
||||
|
||||
|
||||
def test_string_concat() raises:
|
||||
var x = "Hello, World"
|
||||
assert_equal(x, "Hello, World")
|
||||
|
||||
|
||||
# --- Raw strings ---
|
||||
|
||||
|
||||
def test_raw_string() raises:
|
||||
var p = r"C:\path\to\file"
|
||||
assert_equal(p, "C:\\path\\to\\file")
|
||||
|
||||
|
||||
# --- Unicode in source ---
|
||||
|
||||
|
||||
def test_unicode_source() raises:
|
||||
var wave = "👋"
|
||||
assert_equal(wave.byte_length(), 4)
|
||||
|
||||
|
||||
# --- Unicode escapes ---
|
||||
|
||||
|
||||
def test_unicode_escapes() raises:
|
||||
assert_equal("\U0001F44B", "👋")
|
||||
assert_equal("\u20AC", "€")
|
||||
assert_equal("\u00A9", "©")
|
||||
|
||||
|
||||
# --- Escape sequences ---
|
||||
|
||||
|
||||
def test_escape_sequences() raises:
|
||||
assert_equal("\n", "\x0A")
|
||||
assert_equal("\t", "\x09")
|
||||
assert_equal("\r", "\x0D")
|
||||
assert_equal("\\", "\x5C")
|
||||
assert_equal('"', "\x22")
|
||||
assert_equal("\0", "\x00")
|
||||
assert_equal("\101", "A") # octal 101 = 65 = 'A'
|
||||
|
||||
|
||||
# --- Triple-quoted line continuation ---
|
||||
|
||||
|
||||
def test_triple_line_continuation() raises:
|
||||
var x = """\
|
||||
No leading newline.\
|
||||
"""
|
||||
assert_equal(x.find("\n"), -1) # no newline survives
|
||||
|
||||
|
||||
# --- T-string interpolation ---
|
||||
|
||||
|
||||
def test_t_string_basic() raises:
|
||||
var name = "World"
|
||||
var greeting = String(t"Hello, {name}!")
|
||||
assert_equal(greeting, "Hello, World!")
|
||||
assert_equal(String(t"1 + 1 = {1 + 1}"), "1 + 1 = 2")
|
||||
|
||||
|
||||
# --- T-string literal braces ---
|
||||
|
||||
|
||||
def test_t_string_braces() raises:
|
||||
assert_equal(
|
||||
String(t"Use {{braces}} in t-strings"),
|
||||
"Use {braces} in t-strings",
|
||||
)
|
||||
|
||||
|
||||
# --- Nested t-strings ---
|
||||
|
||||
|
||||
def test_t_string_nested() raises:
|
||||
var name = "world"
|
||||
var greeting = String(t"Hello, {t"dear {name}"}!")
|
||||
assert_equal(greeting, "Hello, dear world!")
|
||||
|
||||
|
||||
# --- Boolean literals ---
|
||||
|
||||
|
||||
def test_boolean() raises:
|
||||
var x = True
|
||||
var y = False
|
||||
assert_equal(x, True)
|
||||
assert_equal(y, False)
|
||||
assert_equal(x and not y, True)
|
||||
|
||||
|
||||
# --- None literal ---
|
||||
|
||||
# Not testable
|
||||
# def test_none() raises:
|
||||
# var x: NoneType = None
|
||||
# assert_equal(Bool(x), False)
|
||||
|
||||
|
||||
# --- Self literal ---
|
||||
|
||||
|
||||
@fieldwise_init
|
||||
struct Point:
|
||||
var x: Float64
|
||||
var y: Float64
|
||||
|
||||
@staticmethod
|
||||
def create() -> Self:
|
||||
return Self(0.0, 0.0)
|
||||
|
||||
def distance(self) -> Float64:
|
||||
return sqrt(self.x**2 + self.y**2)
|
||||
|
||||
|
||||
def test_self_literal() raises:
|
||||
var p = Point.create()
|
||||
assert_equal(p.x, 0.0)
|
||||
assert_equal(p.y, 0.0)
|
||||
var q = Point(3.0, 4.0)
|
||||
assert_equal(q.distance(), 5.0)
|
||||
|
||||
|
||||
# --- Ellipsis as required trait method ---
|
||||
|
||||
|
||||
trait Drawable:
|
||||
def draw(self) -> None:
|
||||
...
|
||||
|
||||
|
||||
@fieldwise_init
|
||||
struct Circle(Drawable):
|
||||
var radius: Float64
|
||||
|
||||
def draw(self) -> None:
|
||||
pass
|
||||
|
||||
|
||||
def test_ellipsis_trait() raises:
|
||||
var c = Circle(1.0)
|
||||
c.draw()
|
||||
assert_equal(c.radius, 1.0)
|
||||
|
||||
|
||||
def main() raises:
|
||||
test_integer_bases()
|
||||
test_integer_underscores()
|
||||
test_float_forms()
|
||||
test_string_quotes()
|
||||
test_string_concat()
|
||||
test_raw_string()
|
||||
test_unicode_source()
|
||||
test_unicode_escapes()
|
||||
test_escape_sequences()
|
||||
test_triple_line_continuation()
|
||||
test_t_string_basic()
|
||||
test_t_string_braces()
|
||||
test_t_string_nested()
|
||||
test_boolean()
|
||||
# test_none()
|
||||
test_self_literal()
|
||||
test_ellipsis_trait()
|
||||
@@ -0,0 +1,346 @@
|
||||
# ===----------------------------------------------------------------------=== #
|
||||
# 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 numeric-types.mdx code examples.
|
||||
#
|
||||
# Not tested (no runnable behavior to assert from this file):
|
||||
# - `reflect[type_of(a)].name()` prints (Int naming demos)
|
||||
# - `Float8` arithmetic (requires GPU; covered in the support-matrix
|
||||
# table; CPU execution is unsupported)
|
||||
# - `Float4_e2m1fn` operations (requires NVIDIA Blackwell)
|
||||
# - `BFloat16` arithmetic on Apple Silicon (unsupported per doc)
|
||||
# - `comptime big = 2 ** 200` materialization (IntLiteral arbitrary
|
||||
# precision; no straightforward runtime assertion)
|
||||
from std.testing import assert_equal
|
||||
from std.sys import bit_width_of
|
||||
|
||||
# --- SIMD construction and broadcast multiply ---
|
||||
|
||||
|
||||
def test_simd_broadcast_mul() raises:
|
||||
var v = SIMD[.float32, 4](1.0, 2.0, 3.0, 4.0)
|
||||
var doubled = v * 2.0
|
||||
assert_equal(doubled[0], 2.0)
|
||||
assert_equal(doubled[1], 4.0)
|
||||
assert_equal(doubled[2], 6.0)
|
||||
assert_equal(doubled[3], 8.0)
|
||||
|
||||
|
||||
# --- Element access by lane ---
|
||||
|
||||
|
||||
def test_simd_element_access() raises:
|
||||
var v = SIMD[.float32, 4](1.0, 2.0, 3.0, 4.0)
|
||||
assert_equal(v[0], 1.0)
|
||||
v[0] = 5.0
|
||||
assert_equal(v[0], 5.0)
|
||||
|
||||
|
||||
# --- Element-wise arithmetic ---
|
||||
|
||||
|
||||
def test_simd_arithmetic() raises:
|
||||
var a = SIMD[.float32, 4](1.0, 2.0, 3.0, 4.0)
|
||||
var b = SIMD[.float32, 4](5.0, 6.0, 7.0, 8.0)
|
||||
var sum = a + b
|
||||
assert_equal(sum[0], 6.0)
|
||||
assert_equal(sum[3], 12.0)
|
||||
var prod = a * b
|
||||
assert_equal(prod[0], 5.0)
|
||||
assert_equal(prod[3], 32.0)
|
||||
|
||||
|
||||
# --- Reductions ---
|
||||
|
||||
|
||||
def test_simd_reductions() raises:
|
||||
var a = SIMD[.float32, 4](1.0, 2.0, 3.0, 4.0)
|
||||
assert_equal(a.reduce_add(), 10.0)
|
||||
assert_equal(a.reduce_max(), 4.0)
|
||||
assert_equal(a.reduce_min(), 1.0)
|
||||
|
||||
|
||||
# --- Casting between SIMD dtypes ---
|
||||
|
||||
|
||||
def test_simd_cast() raises:
|
||||
var a = SIMD[.float32, 4](1.0, 2.0, 3.0, 4.0)
|
||||
var ints = a.cast[.int32]()
|
||||
assert_equal(ints[0], 1)
|
||||
assert_equal(ints[3], 4)
|
||||
var wide = a.cast[.float64]()
|
||||
assert_equal(wide[0], 1.0)
|
||||
assert_equal(wide[3], 4.0)
|
||||
var tiny = a.cast[.float16]()
|
||||
assert_equal(tiny[0], 1.0)
|
||||
assert_equal(tiny[3], 4.0)
|
||||
|
||||
|
||||
# --- Clamp (both bounds inclusive) ---
|
||||
|
||||
|
||||
def test_simd_clamp() raises:
|
||||
var a = SIMD[.float32, 4](1.0, 2.0, 3.0, 4.0)
|
||||
var clamped = a.clamp(1.5, 3.5)
|
||||
assert_equal(clamped[0], 1.5)
|
||||
assert_equal(clamped[1], 2.0)
|
||||
assert_equal(clamped[2], 3.0)
|
||||
assert_equal(clamped[3], 3.5)
|
||||
|
||||
|
||||
# --- Free-function min / max ---
|
||||
|
||||
|
||||
def test_min_max() raises:
|
||||
var a = SIMD[.float32, 4](1.0, 2.0, 7.0, 4.0)
|
||||
var b = SIMD[.float32, 4](5.0, 1.0, 3.0, 8.0)
|
||||
var minimum = min(a, b)
|
||||
assert_equal(minimum[0], 1.0)
|
||||
assert_equal(minimum[2], 3.0)
|
||||
var maximum = max(a, b)
|
||||
assert_equal(maximum[0], 5.0)
|
||||
assert_equal(maximum[2], 7.0)
|
||||
|
||||
|
||||
# --- Scalar aliases ---
|
||||
|
||||
|
||||
def test_scalar_aliases() raises:
|
||||
var a: Scalar[.float32] = 3.14
|
||||
var b: Float32 = 3.14
|
||||
var c: SIMD[.float32, 1] = 3.14
|
||||
assert_equal(a, b)
|
||||
assert_equal(b, c)
|
||||
|
||||
|
||||
# --- Parameterized numeric function using DType ---
|
||||
|
||||
|
||||
def double[T: DType](x: Scalar[T]) -> Scalar[T]:
|
||||
return x * UInt8(2).cast[T]()
|
||||
|
||||
|
||||
def test_dtype_parameterized() raises:
|
||||
assert_equal(double[.float32](3.5), 7.0)
|
||||
assert_equal(double[.int16](21), 42)
|
||||
|
||||
|
||||
# --- Int constants ---
|
||||
|
||||
|
||||
def test_int_constants() raises:
|
||||
# BITWIDTH is platform-dependent; on supported platforms today it's 64.
|
||||
assert_equal(bit_width_of[DType.int](), 64)
|
||||
assert_equal(Int.MAX, 9223372036854775807)
|
||||
assert_equal(Int.MIN, -9223372036854775808)
|
||||
|
||||
|
||||
# --- Sized integer bounds ---
|
||||
|
||||
|
||||
def test_sized_int_bounds() raises:
|
||||
assert_equal(UInt8.MAX, 255)
|
||||
assert_equal(Int8.MIN, -128)
|
||||
assert_equal(UInt32.MAX, 4294967295)
|
||||
assert_equal(Int32.MIN, -2147483648)
|
||||
assert_equal(SIMD[.int16, 1].MIN, -32768)
|
||||
|
||||
|
||||
# --- Byte is UInt8 ---
|
||||
|
||||
|
||||
def test_byte_alias() raises:
|
||||
var buf: List[Byte] = [0x48, 0x65, 0x6C, 0x6C, 0x6F]
|
||||
assert_equal(len(buf), 5)
|
||||
assert_equal(buf[0], 0x48)
|
||||
# Byte and UInt8 are the same type
|
||||
var b: Byte = 65
|
||||
var u: UInt8 = 65
|
||||
assert_equal(b, u)
|
||||
|
||||
|
||||
# --- Float MAX / MIN / MAX_FINITE / MIN_FINITE ---
|
||||
|
||||
|
||||
def test_float_bounds() raises:
|
||||
# Float32.MAX_FINITE is the largest finite Float32 value
|
||||
var max_f = Float32.MAX_FINITE
|
||||
var min_f = Float32.MIN_FINITE
|
||||
assert_equal(max_f > 0.0, True)
|
||||
assert_equal(min_f < 0.0, True)
|
||||
# MIN_FINITE is the most negative finite value, equal to -MAX_FINITE
|
||||
assert_equal(min_f, -max_f)
|
||||
|
||||
|
||||
# --- Floating-point rounding error (comptime vs runtime) ---
|
||||
|
||||
|
||||
def test_float_rounding() raises:
|
||||
comptime exact = 3.0 * (4.0 / 3.0 - 1.0)
|
||||
var three = 3.0
|
||||
var finite = three * (4.0 / three - 1.0)
|
||||
# Comptime arithmetic is exact, so this is exactly 1.0
|
||||
assert_equal(exact, 1.0)
|
||||
# Runtime arithmetic accumulates rounding error
|
||||
assert_equal(exact == finite, False)
|
||||
|
||||
|
||||
# --- IntLiteral materialization into different types ---
|
||||
|
||||
|
||||
def test_int_literal_materialization() raises:
|
||||
var a: Int = 42
|
||||
var b: Int8 = 42
|
||||
var c: Float32 = 42
|
||||
var d: UInt64 = 1_000_000
|
||||
assert_equal(a, 42)
|
||||
assert_equal(b, 42)
|
||||
assert_equal(c, 42.0)
|
||||
assert_equal(d, 1_000_000)
|
||||
|
||||
|
||||
# --- FloatLiteral materialization into different float types ---
|
||||
|
||||
|
||||
def test_float_literal_materialization() raises:
|
||||
var x: Float32 = 3.14
|
||||
var y: Float64 = 3.14
|
||||
var z: BFloat16 = 0.5
|
||||
# Approximate equality across widths: round-trip through Float64
|
||||
assert_equal(x.cast[.float64]() > 3.13, True)
|
||||
assert_equal(x.cast[.float64]() < 3.15, True)
|
||||
assert_equal(y, 3.14)
|
||||
assert_equal(z, 0.5)
|
||||
|
||||
|
||||
# --- FloatLiteral special-value constants ---
|
||||
|
||||
|
||||
def test_float_literal_specials() raises:
|
||||
# FloatLiteral exposes nan, infinity, negative_infinity, negative_zero
|
||||
assert_equal(FloatLiteral.nan.is_nan(), True)
|
||||
assert_equal(FloatLiteral.negative_zero.is_neg_zero(), True)
|
||||
# infinity > any finite Float64
|
||||
var inf: Float64 = FloatLiteral.infinity
|
||||
assert_equal(inf > 1.0e308, True)
|
||||
# negative_infinity < any finite Float64
|
||||
var neg_inf: Float64 = FloatLiteral.negative_infinity
|
||||
assert_equal(neg_inf < -1.0e308, True)
|
||||
|
||||
|
||||
# --- Literals adapt to context type ---
|
||||
|
||||
|
||||
def test_literal_adapts() raises:
|
||||
var x = Float32(1.0)
|
||||
var y = x * 0.5 # 0.5 becomes Float32
|
||||
var z = x + 2 # 2 becomes Float32
|
||||
assert_equal(y, 0.5)
|
||||
assert_equal(z, 3.0)
|
||||
|
||||
|
||||
# --- Explicit constructor conversions ---
|
||||
|
||||
|
||||
def test_explicit_conversions() raises:
|
||||
var i = 42 # Int
|
||||
var f = Float32(i)
|
||||
var u = UInt64(i)
|
||||
var narrow = Int8(i)
|
||||
assert_equal(f, 42.0)
|
||||
assert_equal(u, 42)
|
||||
assert_equal(narrow, 42)
|
||||
|
||||
|
||||
# --- SIMD .cast[] between dtypes ---
|
||||
|
||||
|
||||
def test_cast_method() raises:
|
||||
var a = Float32(3.14)
|
||||
var b = a.cast[.int32]() # Float32 → Int32 (truncates)
|
||||
var c = a.cast[.float64]()
|
||||
assert_equal(b, 3)
|
||||
# Float32 → Float64 widens; some bit-pattern drift is acceptable
|
||||
assert_equal(c > 3.13, True)
|
||||
assert_equal(c < 3.15, True)
|
||||
|
||||
|
||||
# --- Int ↔ SIMD-based via constructors ---
|
||||
|
||||
|
||||
def test_int_simd_roundtrip() raises:
|
||||
var i = 42 # Int
|
||||
var s = Int64(i)
|
||||
var back = Int(s)
|
||||
assert_equal(s, 42)
|
||||
assert_equal(back, 42)
|
||||
|
||||
|
||||
# --- Sharp edge: integer overflow wraps (two's complement) ---
|
||||
|
||||
|
||||
def test_int_overflow_wraps() raises:
|
||||
var x = Int8(127)
|
||||
var y = x + Int8(1) # wraps to -128
|
||||
assert_equal(y, -128)
|
||||
var u = UInt8(255)
|
||||
var v = u + UInt8(1) # wraps to 0
|
||||
assert_equal(v, 0)
|
||||
|
||||
|
||||
# --- Sharp edge: float-to-int truncates toward zero ---
|
||||
|
||||
|
||||
def test_float_to_int_truncates() raises:
|
||||
assert_equal(Int(Float32(3.9)), 3)
|
||||
assert_equal(Int(Float32(-3.9)), -3)
|
||||
|
||||
|
||||
# --- Sharp edge: NaN comparison always returns False ---
|
||||
|
||||
|
||||
def test_nan_comparisons() raises:
|
||||
var x = Float32.MAX_FINITE * 2.0 # +inf (overflow)
|
||||
var nan = x - x # inf - inf = NaN
|
||||
# NaN is never equal to itself
|
||||
assert_equal(nan == nan, False)
|
||||
# NaN comparisons of all kinds return False
|
||||
assert_equal(nan < 0.0, False)
|
||||
assert_equal(nan > 0.0, False)
|
||||
|
||||
|
||||
def main() raises:
|
||||
test_simd_broadcast_mul()
|
||||
test_simd_element_access()
|
||||
test_simd_arithmetic()
|
||||
test_simd_reductions()
|
||||
test_simd_cast()
|
||||
test_simd_clamp()
|
||||
test_min_max()
|
||||
test_scalar_aliases()
|
||||
test_dtype_parameterized()
|
||||
test_int_constants()
|
||||
test_sized_int_bounds()
|
||||
test_byte_alias()
|
||||
test_float_bounds()
|
||||
test_float_rounding()
|
||||
test_int_literal_materialization()
|
||||
test_float_literal_materialization()
|
||||
test_float_literal_specials()
|
||||
test_literal_adapts()
|
||||
test_explicit_conversions()
|
||||
test_cast_method()
|
||||
test_int_simd_roundtrip()
|
||||
test_int_overflow_wraps()
|
||||
test_float_to_int_truncates()
|
||||
test_nan_comparisons()
|
||||
@@ -0,0 +1,406 @@
|
||||
# ===----------------------------------------------------------------------=== #
|
||||
# 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 simple-statements.mdx code examples.
|
||||
#
|
||||
# Not tested (intentional errors, warning-only forms, interactive
|
||||
# constructs, or style counter-examples):
|
||||
# - `x + y` unused-result example (warning only, no runtime behavior)
|
||||
# - `print("hello")` / `trigger()` side-effect placeholders (no
|
||||
# observable state to assert)
|
||||
# - `import numpy as np` (Python interop setup out of scope)
|
||||
# - `from std.math import *` (wildcard import is an anti-pattern to
|
||||
# check into source)
|
||||
# - `var x` alone (intentional error: must have type or initializer)
|
||||
# - Module-scope bare `return 42` (intentional error)
|
||||
# - Module-scope `raise Error("oops")` outside try (intentional error)
|
||||
# - `var temperature, name = 98.6, "Bob"` counter-example (style
|
||||
# guidance only; both forms compile)
|
||||
# - `x @= m` matmul augmented op (requires a struct with
|
||||
# `__imatmul__`; covered in operators tests)
|
||||
from std.testing import assert_equal
|
||||
|
||||
|
||||
# --- Stubs referenced by code examples ---
|
||||
|
||||
|
||||
def compute() -> Int:
|
||||
return 7
|
||||
|
||||
|
||||
def update() -> Int:
|
||||
return 0
|
||||
|
||||
|
||||
def returns_pair() -> Tuple[Int, Int]:
|
||||
return (1, 2)
|
||||
|
||||
|
||||
def perform_some_test() -> Bool:
|
||||
return True
|
||||
|
||||
|
||||
def log(e: Error):
|
||||
pass
|
||||
|
||||
|
||||
def validate(value: Int) raises -> Bool:
|
||||
if value < 0:
|
||||
raise Error("value must be non-negative")
|
||||
return True
|
||||
|
||||
|
||||
# --- Expression statements: discarding a result ---
|
||||
|
||||
|
||||
def test_underscore_discard() raises:
|
||||
_ = update()
|
||||
|
||||
|
||||
# --- Assignment statements: var with inference ---
|
||||
|
||||
|
||||
def test_var_inference() raises:
|
||||
var x = 42
|
||||
var name = "Alice"
|
||||
var result = compute()
|
||||
assert_equal(x, 42)
|
||||
assert_equal(name, "Alice")
|
||||
assert_equal(result, 7)
|
||||
|
||||
|
||||
# --- Assignment statements: ref binding ---
|
||||
|
||||
|
||||
def test_ref_binding_read() raises:
|
||||
var my_list = [10, 20, 30, 40]
|
||||
ref y = my_list[3]
|
||||
assert_equal(y, 40)
|
||||
|
||||
|
||||
def test_ref_binding_write_through() raises:
|
||||
var my_list = [10, 20, 30, 40]
|
||||
ref y = my_list[3]
|
||||
y = 99
|
||||
assert_equal(my_list[3], 99)
|
||||
|
||||
|
||||
def test_ref_binding_observe_underlying() raises:
|
||||
var my_list = [10, 20, 30, 40]
|
||||
ref y = my_list[3]
|
||||
my_list[3] = 77
|
||||
assert_equal(y, 77)
|
||||
|
||||
|
||||
# --- Assignment statements: annotated ---
|
||||
|
||||
|
||||
def test_annotated_assignment() raises:
|
||||
var x: Int = 42
|
||||
var name: String = "Alice"
|
||||
var values: List[Float64] = []
|
||||
assert_equal(x, 42)
|
||||
assert_equal(name, "Alice")
|
||||
assert_equal(len(values), 0)
|
||||
|
||||
|
||||
def test_var_type_only_then_assign() raises:
|
||||
var x: Int
|
||||
x = 42
|
||||
assert_equal(x, 42)
|
||||
|
||||
|
||||
# --- Assignment statements: comptime type alias ---
|
||||
|
||||
|
||||
def test_comptime_type_alias() raises:
|
||||
comptime Vec3 = List[Float64]
|
||||
var position: Vec3 = [0.0, 0.0, 0.0]
|
||||
assert_equal(len(position), 3)
|
||||
assert_equal(position[0], 0.0)
|
||||
|
||||
|
||||
# --- Multiple assignment: chained, same value ---
|
||||
|
||||
|
||||
def test_chained_same_value() raises:
|
||||
var x = var y = var z = "Hello"
|
||||
assert_equal(x, "Hello")
|
||||
assert_equal(y, "Hello")
|
||||
assert_equal(z, "Hello")
|
||||
|
||||
|
||||
# --- Multiple assignment: chained ref/var mix ---
|
||||
|
||||
|
||||
def test_chained_ref_var_mix() raises:
|
||||
ref a = var b = var c = "Hello"
|
||||
assert_equal(a, "Hello")
|
||||
assert_equal(b, "Hello")
|
||||
assert_equal(c, "Hello")
|
||||
a = "World"
|
||||
# `ref a` is bound to `b`'s storage; writing through `a` mutates `b`.
|
||||
assert_equal(b, "World")
|
||||
# `c` got its own copy of "Hello" and is independent.
|
||||
assert_equal(c, "Hello")
|
||||
|
||||
|
||||
# --- Multiple assignment: destructuring ---
|
||||
|
||||
|
||||
def test_destructuring_bare() raises:
|
||||
var a, b = 1, 2
|
||||
assert_equal(a, 1)
|
||||
assert_equal(b, 2)
|
||||
|
||||
|
||||
def test_destructuring_parenthesized() raises:
|
||||
var (c, d) = (1, 2)
|
||||
assert_equal(c, 1)
|
||||
assert_equal(d, 2)
|
||||
|
||||
|
||||
def test_tuple_return_unpack() raises:
|
||||
var e, f = returns_pair()
|
||||
assert_equal(e, 1)
|
||||
assert_equal(f, 2)
|
||||
|
||||
|
||||
# --- Simple swaps ---
|
||||
|
||||
|
||||
def test_simple_swap() raises:
|
||||
var a, b, c = 1, 2, 3
|
||||
a, b, c = c, a, b
|
||||
assert_equal(a, 3)
|
||||
assert_equal(b, 1)
|
||||
assert_equal(c, 2)
|
||||
|
||||
|
||||
# --- Augmented assignment ---
|
||||
|
||||
|
||||
def test_augmented_arithmetic_int() raises:
|
||||
var x = 10
|
||||
x += 5
|
||||
assert_equal(x, 15)
|
||||
x -= 2
|
||||
assert_equal(x, 13)
|
||||
x *= 3
|
||||
assert_equal(x, 39)
|
||||
x //= 2
|
||||
assert_equal(x, 19)
|
||||
x %= 7
|
||||
assert_equal(x, 5)
|
||||
x **= 2
|
||||
assert_equal(x, 25)
|
||||
|
||||
|
||||
def test_augmented_float_div() raises:
|
||||
var x: Float64 = 20.0
|
||||
x /= 4.0
|
||||
assert_equal(x, 5.0)
|
||||
|
||||
|
||||
def test_augmented_bitwise() raises:
|
||||
var bits = 0b1100
|
||||
bits &= 0b1010
|
||||
assert_equal(bits, 0b1000)
|
||||
bits |= 0b0011
|
||||
assert_equal(bits, 0b1011)
|
||||
bits ^= 0b1111
|
||||
assert_equal(bits, 0b0100)
|
||||
bits <<= 2
|
||||
assert_equal(bits, 0b10000)
|
||||
bits >>= 1
|
||||
assert_equal(bits, 0b1000)
|
||||
|
||||
|
||||
# --- pass statement ---
|
||||
|
||||
|
||||
def not_ready():
|
||||
pass
|
||||
|
||||
|
||||
struct Empty:
|
||||
pass
|
||||
|
||||
|
||||
def test_pass_in_function() raises:
|
||||
not_ready()
|
||||
|
||||
|
||||
# --- return statement ---
|
||||
|
||||
|
||||
def greet(name: String):
|
||||
if not name:
|
||||
return
|
||||
print(t"Hello, {name}!")
|
||||
|
||||
|
||||
def get_value() -> Int:
|
||||
return 42
|
||||
|
||||
|
||||
def early_exit(items: List[Int], target: Int) -> Bool:
|
||||
for item in items:
|
||||
if item == target:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def test_return_void_early() raises:
|
||||
greet("")
|
||||
|
||||
|
||||
def test_return_value() raises:
|
||||
assert_equal(get_value(), 42)
|
||||
|
||||
|
||||
def test_early_exit_found() raises:
|
||||
var items: List = [1, 2, 3, 4, 5]
|
||||
assert_equal(early_exit(items, 3), True)
|
||||
|
||||
|
||||
def test_early_exit_not_found() raises:
|
||||
var items: List = [1, 2, 3, 4, 5]
|
||||
assert_equal(early_exit(items, 99), False)
|
||||
|
||||
|
||||
# --- raise statement ---
|
||||
|
||||
|
||||
def test_validate_happy_path() raises:
|
||||
assert_equal(validate(5), True)
|
||||
|
||||
|
||||
def test_validate_raises() raises:
|
||||
var raised = False
|
||||
try:
|
||||
_ = validate(-1)
|
||||
except e:
|
||||
raised = True
|
||||
assert_equal(raised, True)
|
||||
|
||||
|
||||
def mitigate_risk():
|
||||
try:
|
||||
if not perform_some_test():
|
||||
raise Error("test failed")
|
||||
except e:
|
||||
log(e)
|
||||
|
||||
|
||||
def test_mitigate_risk_no_raise() raises:
|
||||
# `perform_some_test` stub returns True, so no error is raised
|
||||
# inside `mitigate_risk`. The function itself does not propagate.
|
||||
mitigate_risk()
|
||||
|
||||
|
||||
def reraise_through(value: Int) raises:
|
||||
try:
|
||||
_ = validate(value)
|
||||
except e:
|
||||
raise # Bare raise re-raises the current error.
|
||||
|
||||
|
||||
def test_bare_reraise() raises:
|
||||
var raised = False
|
||||
try:
|
||||
reraise_through(-1)
|
||||
except e:
|
||||
raised = True
|
||||
assert_equal(raised, True)
|
||||
|
||||
|
||||
# --- break / continue ---
|
||||
|
||||
|
||||
def collect_loop_values() -> List[Int]:
|
||||
var out = List[Int]()
|
||||
for x in range(10):
|
||||
if x == 5:
|
||||
break
|
||||
if x % 2 == 0:
|
||||
continue
|
||||
out.append(x)
|
||||
return out^
|
||||
|
||||
|
||||
def test_break_continue() raises:
|
||||
var result = collect_loop_values()
|
||||
assert_equal(len(result), 2)
|
||||
assert_equal(result[0], 1)
|
||||
assert_equal(result[1], 3)
|
||||
|
||||
|
||||
# --- comptime declarations ---
|
||||
|
||||
|
||||
comptime SIZE = 256
|
||||
comptime MAX = SIZE * 2
|
||||
|
||||
|
||||
def test_comptime_constants() raises:
|
||||
assert_equal(SIZE, 256)
|
||||
assert_equal(MAX, 512)
|
||||
|
||||
|
||||
# Trait composition alias and a trait with an associated comptime type.
|
||||
# Declaring these at module scope is the test: the file compiling is the
|
||||
# verification that the syntax and the semantic check pass.
|
||||
comptime Permissive = ImplicitlyCopyable & Deinitable
|
||||
|
||||
|
||||
trait SimpleTrait(Writable):
|
||||
comptime Element = Permissive
|
||||
|
||||
|
||||
def test_comptime_trait_declared() raises:
|
||||
# No runtime assertion needed; module-scope declarations above are
|
||||
# what's under test.
|
||||
pass
|
||||
|
||||
|
||||
def main() raises:
|
||||
test_underscore_discard()
|
||||
test_var_inference()
|
||||
test_ref_binding_read()
|
||||
test_ref_binding_write_through()
|
||||
test_ref_binding_observe_underlying()
|
||||
test_annotated_assignment()
|
||||
test_var_type_only_then_assign()
|
||||
test_comptime_type_alias()
|
||||
test_chained_same_value()
|
||||
test_chained_ref_var_mix()
|
||||
test_destructuring_bare()
|
||||
test_destructuring_parenthesized()
|
||||
test_tuple_return_unpack()
|
||||
test_simple_swap()
|
||||
test_augmented_arithmetic_int()
|
||||
test_augmented_float_div()
|
||||
test_augmented_bitwise()
|
||||
test_pass_in_function()
|
||||
test_return_void_early()
|
||||
test_return_value()
|
||||
test_early_exit_found()
|
||||
test_early_exit_not_found()
|
||||
test_validate_happy_path()
|
||||
test_validate_raises()
|
||||
test_mitigate_risk_no_raise()
|
||||
test_bare_reraise()
|
||||
test_break_continue()
|
||||
test_comptime_constants()
|
||||
test_comptime_trait_declared()
|
||||
@@ -0,0 +1,281 @@
|
||||
# ===----------------------------------------------------------------------=== #
|
||||
# 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_struct_declarations.mojo
|
||||
# Tests for struct-declarations.mdx code examples.
|
||||
# Skip: nested struct error, field without type error, dynamic
|
||||
# trait field error, fieldwise_init synthesis failure
|
||||
# (Alpha/Color), Incomplete(Sized) missing method,
|
||||
# Box without Deinitable abandoned error,
|
||||
# Unsound(Copyable) with SomeMoveOnlyType, default
|
||||
# method conflicts (struct S(A & B) constructed to fail),
|
||||
# missing self error, __init__ without out self error,
|
||||
# recursive Node error, __deinit__ snippet (no standalone
|
||||
# example), @staticmethod snippet (error pair only),
|
||||
# NotWritable example (constructed to fail), conditional
|
||||
# conformance struct snippets (hypothetical trait names
|
||||
# like GPUComputable/FloatMath/Printable, no def main()).
|
||||
from std.testing import assert_equal
|
||||
from std.math import sqrt
|
||||
|
||||
|
||||
# --- Point with distance ---
|
||||
|
||||
|
||||
struct Point_1:
|
||||
var x: Int
|
||||
var y: Int
|
||||
|
||||
def __init__(out self, x: Int, y: Int):
|
||||
self.x = x
|
||||
self.y = y
|
||||
|
||||
def distance(self) -> Float64:
|
||||
return sqrt(Float64(self.x * self.x + self.y * self.y))
|
||||
|
||||
|
||||
def test_point_distance() raises:
|
||||
var p = Point_1(3, 4)
|
||||
assert_equal(p.distance(), 5.0)
|
||||
|
||||
|
||||
# --- Minimal struct ---
|
||||
|
||||
|
||||
@fieldwise_init
|
||||
struct ValidationError:
|
||||
pass
|
||||
|
||||
|
||||
def test_validation_error():
|
||||
_ = ValidationError()
|
||||
|
||||
|
||||
# --- Color with manual __init__ ---
|
||||
|
||||
|
||||
struct Color_1:
|
||||
var r: UInt8
|
||||
var g: UInt8
|
||||
var b: UInt8
|
||||
|
||||
def __init__(out self, r: UInt8, g: UInt8, b: UInt8):
|
||||
(self.r, self.g, self.b) = (r, g, b)
|
||||
|
||||
|
||||
def test_color_manual() raises:
|
||||
var c = Color_1(255, 0, 0)
|
||||
assert_equal(c.r, 255)
|
||||
assert_equal(c.g, 0)
|
||||
assert_equal(c.b, 0)
|
||||
|
||||
|
||||
# --- Field type from parameter ---
|
||||
|
||||
|
||||
@fieldwise_init
|
||||
struct Sound[T: Writable & Copyable & Deinitable]:
|
||||
var item: Self.T
|
||||
|
||||
|
||||
def test_field_type_parameter() raises:
|
||||
var g = Sound[Int](item=42)
|
||||
assert_equal(g.item, 42)
|
||||
|
||||
|
||||
# --- Color with @fieldwise_init ---
|
||||
|
||||
|
||||
@fieldwise_init
|
||||
struct Color_2:
|
||||
var r: UInt8
|
||||
var g: UInt8
|
||||
var b: UInt8
|
||||
|
||||
|
||||
def test_color_fieldwise() raises:
|
||||
var color = Color_2(255, 0, 0)
|
||||
assert_equal(color.r, 255)
|
||||
assert_equal(color.g, 0)
|
||||
assert_equal(color.b, 0)
|
||||
|
||||
|
||||
# --- Parameterized Pair ---
|
||||
|
||||
|
||||
@fieldwise_init
|
||||
struct Pair_1[T: Copyable & Deinitable]:
|
||||
var first: Self.T
|
||||
var second: Self.T
|
||||
|
||||
|
||||
def test_parameterized_pair() raises:
|
||||
var p = Pair_1[Int](first=1, second=2)
|
||||
assert_equal(p.first, 1)
|
||||
assert_equal(p.second, 2)
|
||||
|
||||
|
||||
# --- Defaulted parameters ---
|
||||
|
||||
|
||||
struct SplatList[
|
||||
T: ImplicitlyCopyable & Deinitable,
|
||||
*,
|
||||
fill: T,
|
||||
length: Int = 5,
|
||||
]:
|
||||
var items: List[Self.T]
|
||||
|
||||
def __init__(out self):
|
||||
self.items = List[Self.T](length=Self.length, fill=Self.fill)
|
||||
|
||||
|
||||
def test_defaulted_parameters() raises:
|
||||
var l = SplatList[Int, fill=42]()
|
||||
assert_equal(len(l.items), 5)
|
||||
assert_equal(l.items[0], 42)
|
||||
assert_equal(l.items[4], 42)
|
||||
|
||||
|
||||
# --- Trait conformance ---
|
||||
|
||||
|
||||
@fieldwise_init
|
||||
struct MyInt(Copyable, Writable):
|
||||
var value: Int
|
||||
|
||||
def write_to[W: Writer](self, mut writer: W):
|
||||
writer.write(self.value)
|
||||
|
||||
|
||||
def test_trait_conformance() raises:
|
||||
var my_int = MyInt(42)
|
||||
assert_equal(String(my_int), "42")
|
||||
|
||||
|
||||
# --- Conformance with where clause ---
|
||||
|
||||
|
||||
@fieldwise_init
|
||||
struct Pair_2[T: Copyable & Deinitable](
|
||||
Equatable where conforms_to(T, Equatable)
|
||||
):
|
||||
var first: Self.T
|
||||
var second: Self.T
|
||||
|
||||
|
||||
def test_conformance_where() raises:
|
||||
var a = Pair_2[Int](first=1, second=2)
|
||||
var b = Pair_2[Int](first=1, second=2)
|
||||
var c = Pair_2[Int](first=3, second=4)
|
||||
assert_equal(a == b, True)
|
||||
assert_equal(a == c, False)
|
||||
|
||||
|
||||
# --- Mixed trait list: Equatable + Writable conditional, Copyable plain ---
|
||||
|
||||
|
||||
@fieldwise_init
|
||||
struct Pair_Mixed[T: Copyable & Deinitable](
|
||||
Copyable,
|
||||
Equatable where conforms_to(T, Equatable),
|
||||
Writable where conforms_to(T, Writable),
|
||||
):
|
||||
var first: Self.T
|
||||
var second: Self.T
|
||||
|
||||
|
||||
def test_mixed_trait_list() raises:
|
||||
var pair1 = Pair_Mixed(first=1, second=2)
|
||||
var pair2 = Pair_Mixed(first=1, second=2)
|
||||
var pair3 = Pair_Mixed(first=3, second=4)
|
||||
assert_equal(pair1 == pair2, True)
|
||||
assert_equal(pair1 == pair3, False)
|
||||
var pair4 = pair1.copy()
|
||||
_ = pair4
|
||||
|
||||
|
||||
# --- Box with Deinitable ---
|
||||
|
||||
|
||||
@fieldwise_init
|
||||
struct Box[T: Copyable & Deinitable](Equatable where conforms_to(T, Equatable)):
|
||||
var item: Self.T
|
||||
|
||||
|
||||
def test_box_implicit_destructible() raises:
|
||||
var box = Box(42)
|
||||
assert_equal(box.item, 42)
|
||||
|
||||
|
||||
# --- Point with Float64 ---
|
||||
|
||||
|
||||
struct Point_2:
|
||||
var x: Float64
|
||||
var y: Float64
|
||||
|
||||
def __init__(out self, x: Float64, y: Float64):
|
||||
(self.x, self.y) = (x, y)
|
||||
|
||||
|
||||
def test_point_float() raises:
|
||||
var p = Point_2(3.0, 4.0)
|
||||
assert_equal(p.x, 3.0)
|
||||
assert_equal(p.y, 4.0)
|
||||
|
||||
|
||||
# --- comptime members: constants, type aliases, parameterized aliases ---
|
||||
|
||||
|
||||
@fieldwise_init
|
||||
struct Matrix2D[dtype: DType, w: Int, h: Int]:
|
||||
pass
|
||||
|
||||
|
||||
@fieldwise_init
|
||||
struct CompTest[dtype: DType]:
|
||||
comptime default_size = 1024
|
||||
comptime DefaultMatrixType = Matrix2D[
|
||||
Self.dtype, Self.default_size, Self.default_size
|
||||
]
|
||||
comptime SquareMatrixType[size: Int] = Matrix2D[Self.dtype, size, size]
|
||||
|
||||
|
||||
def test_comptime_members() raises:
|
||||
# Access constants on the type and on an instance.
|
||||
assert_equal(CompTest[.int32].default_size, 1024)
|
||||
assert_equal(CompTest[.int32]().default_size, 1024)
|
||||
# Type aliases via comptime resolve to concrete types.
|
||||
var _default: CompTest[.int32].DefaultMatrixType = Matrix2D[
|
||||
DType.int32, 1024, 1024
|
||||
]()
|
||||
# Parameterized comptime members specialize at use site.
|
||||
var _square: CompTest[.int32].SquareMatrixType[10] = Matrix2D[
|
||||
DType.int32, 10, 10
|
||||
]()
|
||||
|
||||
|
||||
def main() raises:
|
||||
test_point_distance()
|
||||
test_validation_error()
|
||||
test_color_manual()
|
||||
test_field_type_parameter()
|
||||
test_color_fieldwise()
|
||||
test_parameterized_pair()
|
||||
test_defaulted_parameters()
|
||||
test_trait_conformance()
|
||||
test_conformance_where()
|
||||
test_mixed_trait_list()
|
||||
test_box_implicit_destructible()
|
||||
test_point_float()
|
||||
test_comptime_members()
|
||||
@@ -0,0 +1,318 @@
|
||||
# ===----------------------------------------------------------------------=== #
|
||||
# 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_trait_declarations.mojo
|
||||
# Tests for trait-declarations.mdx code examples.
|
||||
# Skip: nested trait error, parameterized trait error, var field
|
||||
# error, where clause error, pass vs ... error, comptime
|
||||
# without initializer errors, missing method errors, missing
|
||||
# required member errors, type mismatch errors, default
|
||||
# method conflict errors, non-conforming argument errors.
|
||||
# Print-only tests: test_required_methods, test_provided_methods,
|
||||
# test_able_to_say_hello, test_parameter_level_bounds, and
|
||||
# test_fieldwise_bounds use print() rather than assertions
|
||||
# because asserting on string representations is fragile
|
||||
# (reflection-based output format can change). These tests
|
||||
# still verify compilation, trait constraint satisfaction, and
|
||||
# dispatch — successful execution without raising is the signal.
|
||||
from std.testing import assert_equal
|
||||
|
||||
|
||||
# --- Required methods ---
|
||||
|
||||
|
||||
trait RequiredMethods:
|
||||
def required_method(self):
|
||||
...
|
||||
|
||||
@staticmethod
|
||||
def required_static_method():
|
||||
...
|
||||
|
||||
|
||||
@fieldwise_init
|
||||
struct SampleStruct_1(RequiredMethods):
|
||||
def required_method(self):
|
||||
print("Required method")
|
||||
|
||||
@staticmethod
|
||||
def required_static_method():
|
||||
print("Required static method")
|
||||
|
||||
|
||||
def test_required_methods():
|
||||
var s = SampleStruct_1()
|
||||
s.required_method() # Required method
|
||||
SampleStruct_1.required_static_method() # Required static method
|
||||
|
||||
|
||||
# --- Provided methods ---
|
||||
|
||||
|
||||
trait ProvidedMethods:
|
||||
def provided_method(self):
|
||||
print("Provided method")
|
||||
|
||||
@staticmethod
|
||||
def provided_static_method():
|
||||
print("Provided static method")
|
||||
|
||||
|
||||
@fieldwise_init
|
||||
struct SampleStruct_2(ProvidedMethods):
|
||||
def provided_method(self):
|
||||
print("Overridden provided method")
|
||||
|
||||
|
||||
def test_provided_methods():
|
||||
var sample = SampleStruct_2()
|
||||
sample.provided_method() # Overridden provided method
|
||||
SampleStruct_2.provided_static_method() # Provided static method
|
||||
|
||||
|
||||
# --- Default return value ---
|
||||
|
||||
|
||||
trait Describable:
|
||||
def describe(self) -> String:
|
||||
return "no description"
|
||||
|
||||
|
||||
@fieldwise_init
|
||||
struct Undescribed(Describable):
|
||||
pass
|
||||
|
||||
|
||||
def test_describable() raises:
|
||||
var u = Undescribed()
|
||||
assert_equal(u.describe(), "no description")
|
||||
|
||||
|
||||
# --- Empty struct with default methods ---
|
||||
|
||||
|
||||
trait AbleToSayHello:
|
||||
def say_hello(self):
|
||||
print("Hello!")
|
||||
|
||||
|
||||
@fieldwise_init
|
||||
struct SampleStruct_3(AbleToSayHello):
|
||||
pass
|
||||
|
||||
|
||||
def test_able_to_say_hello():
|
||||
var sample = SampleStruct_3()
|
||||
sample.say_hello() # Hello!
|
||||
|
||||
|
||||
# --- Associated types ---
|
||||
|
||||
|
||||
trait Boxable:
|
||||
comptime Associated: Writable & Copyable & Deinitable
|
||||
|
||||
def unbox(self) -> Self.Associated:
|
||||
...
|
||||
|
||||
|
||||
@fieldwise_init
|
||||
struct ConcreteBox(Boxable):
|
||||
comptime Associated = String
|
||||
var value: Self.Associated
|
||||
|
||||
def unbox(self) -> Self.Associated:
|
||||
return self.value.copy()
|
||||
|
||||
|
||||
def test_associated_types() raises:
|
||||
var box = ConcreteBox(value="Hello")
|
||||
var unboxed = box.unbox()
|
||||
assert_equal(unboxed, "Hello")
|
||||
_ = unboxed^
|
||||
|
||||
|
||||
# --- Associated type ---
|
||||
|
||||
|
||||
comptime Base = Copyable & Deinitable & Writable
|
||||
|
||||
|
||||
@fieldwise_init
|
||||
struct Box_1[T: Base](Boxable):
|
||||
comptime Associated = Self.T
|
||||
var value: Self.Associated
|
||||
|
||||
def unbox(self) -> Self.Associated:
|
||||
return self.value.copy()
|
||||
|
||||
|
||||
def test_associated_type() raises:
|
||||
var box = Box_1[Int](value=42)
|
||||
var unboxed = box.unbox()
|
||||
assert_equal(unboxed, 42)
|
||||
|
||||
|
||||
# --- Comptime constants ---
|
||||
|
||||
|
||||
from std.sys.info import bit_width_of
|
||||
|
||||
comptime BaseElement = Copyable & Deinitable & Writable
|
||||
|
||||
|
||||
trait Test:
|
||||
comptime Element: RegisterPassable
|
||||
comptime element_bitwidth = bit_width_of[Self.Element]()
|
||||
|
||||
|
||||
@fieldwise_init
|
||||
struct SampleStruct_4[T: BaseElement](Test):
|
||||
comptime Element = Int64
|
||||
var x: Self.T
|
||||
|
||||
def show_element_bitwidth(self) raises:
|
||||
assert_equal(Self.element_bitwidth, 64)
|
||||
|
||||
|
||||
def test_comptime_constants() raises:
|
||||
var s = SampleStruct_4[Int64](x=42)
|
||||
s.show_element_bitwidth()
|
||||
assert_equal(s.x, 42)
|
||||
|
||||
|
||||
# --- Required values ---
|
||||
|
||||
|
||||
trait Measurable:
|
||||
comptime unit: StaticString
|
||||
comptime always_positive: Bool
|
||||
|
||||
def get_value(self) -> Float64:
|
||||
...
|
||||
|
||||
|
||||
def validate[T: Measurable](measurement: T) raises:
|
||||
comptime if T.always_positive:
|
||||
if Float64(measurement.get_value()) < 0.0:
|
||||
raise Error(t"{T.unit} cannot be negative")
|
||||
|
||||
|
||||
@fieldwise_init
|
||||
struct Pascals(Measurable):
|
||||
comptime unit: StaticString = "Pa"
|
||||
comptime always_positive: Bool = True
|
||||
var value: Float64
|
||||
|
||||
def get_value(self) -> Float64:
|
||||
return self.value
|
||||
|
||||
|
||||
def test_required_values() raises:
|
||||
validate(Pascals(value=101325.0))
|
||||
|
||||
|
||||
# --- Trait refinement ---
|
||||
|
||||
|
||||
trait Printable:
|
||||
def to_string(self) -> String:
|
||||
...
|
||||
|
||||
|
||||
trait PrettyPrintable(Printable):
|
||||
def to_pretty_string(self) -> String:
|
||||
...
|
||||
|
||||
|
||||
@fieldwise_init
|
||||
struct Box_2[T: Copyable & Writable & Deinitable](PrettyPrintable):
|
||||
var value: Self.T
|
||||
|
||||
def to_string(self) -> String:
|
||||
return String(t"Box({self.value})")
|
||||
|
||||
def to_pretty_string(self) -> String:
|
||||
return String(t"Box with value: {self.value}")
|
||||
|
||||
|
||||
def render[T: PrettyPrintable](item: T):
|
||||
print(item.to_string(), "-", item.to_pretty_string())
|
||||
|
||||
|
||||
def test_trait_refinement() raises:
|
||||
render(Box_2(1)) # Box(1) - Box with value: 1
|
||||
render(Box_2("hello")) # Box(hello) - Box with value: hello
|
||||
assert_equal(Box_2(1).to_string(), "Box(1)")
|
||||
assert_equal(Box_2(1).to_pretty_string(), "Box with value: 1")
|
||||
assert_equal(Box_2("hello").to_string(), "Box(hello)")
|
||||
assert_equal(Box_2("hello").to_pretty_string(), "Box with value: hello")
|
||||
|
||||
|
||||
# --- Parameter-level trait constraints ---
|
||||
|
||||
|
||||
def print_twice[T: Writable & Copyable](value: T):
|
||||
print(value, value)
|
||||
|
||||
|
||||
def test_parameter_level_bounds():
|
||||
print_twice(42) # 42 42
|
||||
print_twice("hi") # hi hi
|
||||
|
||||
|
||||
# --- Struct-level trait constraints ---
|
||||
|
||||
|
||||
@fieldwise_init
|
||||
struct Pair_1[T: Writable & Copyable & Deinitable](Writable):
|
||||
var first: Self.T
|
||||
var second: Self.T
|
||||
|
||||
def write_to[W: Writer](self, mut writer: W):
|
||||
writer.write(t"({self.first}, {self.second})")
|
||||
|
||||
|
||||
def test_struct_level_bounds() raises:
|
||||
var p = Pair_1(1, 2)
|
||||
assert_equal(String(p), "(1, 2)")
|
||||
|
||||
|
||||
# --- Fieldwise trait constraints ---
|
||||
|
||||
|
||||
@fieldwise_init
|
||||
struct Pair_2[T: Copyable & Deinitable](
|
||||
Writable where conforms_to(T, Writable)
|
||||
):
|
||||
var first: Self.T
|
||||
var second: Self.T
|
||||
|
||||
|
||||
def test_fieldwise_bounds() raises:
|
||||
var pair = Pair_2(1, 2)
|
||||
print(pair) # Pair_2[Int](first=1, second=2)
|
||||
|
||||
|
||||
def main() raises:
|
||||
test_required_methods()
|
||||
test_provided_methods()
|
||||
test_describable()
|
||||
test_able_to_say_hello()
|
||||
test_associated_types()
|
||||
test_associated_type()
|
||||
test_comptime_constants()
|
||||
test_required_values()
|
||||
test_trait_refinement()
|
||||
test_parameter_level_bounds()
|
||||
test_struct_level_bounds()
|
||||
test_fieldwise_bounds()
|
||||
@@ -0,0 +1,148 @@
|
||||
# ===----------------------------------------------------------------------=== #
|
||||
# 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 types.mdx code examples.
|
||||
#
|
||||
# Not tested at runtime (intentional):
|
||||
# - `fatal()` is defined to type-check the `Never` example, but it's
|
||||
# never called: invoking `abort()` would terminate the test process.
|
||||
# - The Numeric types and Memory types sections delegate to other
|
||||
# pages and have no standalone runnable code.
|
||||
from std.collections import Set
|
||||
from std.os import abort
|
||||
from std.testing import assert_equal, assert_true
|
||||
from std.utils import Variant
|
||||
|
||||
|
||||
# --- Built-in types and the prelude: set display vs. the Set type ---
|
||||
|
||||
|
||||
def test_set_display_and_type() raises:
|
||||
var primes = {2, 3, 5, 7} # set display: no import needed
|
||||
assert_equal(len(primes), 4)
|
||||
var empty = Set[Int]() # naming Set needs the import
|
||||
assert_equal(len(empty), 0)
|
||||
|
||||
|
||||
# --- String types ---
|
||||
|
||||
|
||||
def test_string_lengths() raises:
|
||||
var wave = String("👋🏽") # waving hand + skin-tone modifier
|
||||
assert_equal(wave.byte_length(), 8)
|
||||
assert_equal(wave.count_codepoints(), 2)
|
||||
assert_equal(wave.count_graphemes(), 1)
|
||||
|
||||
|
||||
# --- Collection types: Optional ---
|
||||
|
||||
|
||||
def test_optional() raises:
|
||||
var maybe: Optional[Int] = 5
|
||||
var present = False
|
||||
if maybe:
|
||||
present = True
|
||||
assert_true(present)
|
||||
assert_equal(maybe.value(), 5)
|
||||
|
||||
var empty: Optional[Int] = None
|
||||
assert_equal(empty.or_else(0), 0)
|
||||
|
||||
|
||||
# --- Collection types: Variant ---
|
||||
|
||||
|
||||
def test_variant() raises:
|
||||
var v = Variant[Int, String](5)
|
||||
assert_equal(v[Int], 5)
|
||||
v.set[String]("text")
|
||||
assert_equal(v[String], "text")
|
||||
|
||||
|
||||
# --- Other built-in types: Bool ---
|
||||
|
||||
|
||||
def test_bool() raises:
|
||||
var flag = True
|
||||
var captured = False
|
||||
if flag:
|
||||
captured = True
|
||||
assert_true(captured)
|
||||
|
||||
|
||||
# --- Other built-in types: Error ---
|
||||
|
||||
|
||||
def parse(s: String) raises -> Int:
|
||||
raise Error("invalid input")
|
||||
|
||||
|
||||
def test_error_raises() raises:
|
||||
var caught = String("")
|
||||
try:
|
||||
_ = parse("bad")
|
||||
except e:
|
||||
caught = String(e)
|
||||
assert_equal(caught, "invalid input")
|
||||
|
||||
|
||||
# --- Other built-in types: Never (type-checked, not invoked) ---
|
||||
|
||||
|
||||
def fatal() -> Never:
|
||||
abort() # never returns
|
||||
|
||||
|
||||
# --- Other built-in types: None ---
|
||||
|
||||
|
||||
def implicit_greet(name: String):
|
||||
print("hello", name)
|
||||
# returns None implicitly
|
||||
|
||||
|
||||
def explicit_greet(name: String) -> None:
|
||||
print("hello", name)
|
||||
# returns None explicitly
|
||||
|
||||
|
||||
def test_none_returns() raises:
|
||||
implicit_greet("implicit")
|
||||
explicit_greet("explicit")
|
||||
|
||||
|
||||
# --- Other built-in types: Slice ---
|
||||
|
||||
|
||||
def test_slice_views() raises:
|
||||
var items: List = [0, 1, 2, 3, 4, 5]
|
||||
var middle = items[1:4] # Span view, [1, 2, 3]
|
||||
assert_equal(len(middle), 3)
|
||||
assert_equal(middle[0], 1)
|
||||
assert_equal(middle[2], 3)
|
||||
|
||||
var strided = items[::2] # new List, [0, 2, 4]
|
||||
assert_equal(len(strided), 3)
|
||||
assert_equal(strided[0], 0)
|
||||
assert_equal(strided[2], 4)
|
||||
|
||||
|
||||
def main() raises:
|
||||
test_set_display_and_type()
|
||||
test_string_lengths()
|
||||
test_optional()
|
||||
test_variant()
|
||||
test_bool()
|
||||
test_error_raises()
|
||||
test_none_returns()
|
||||
test_slice_views()
|
||||
Reference in new issue
Block a user