Baseline: tree as shared
This commit is contained in:
1679 files changed
+1024562
No files matched your search
@@ -0,0 +1,291 @@
|
||||
# ===----------------------------------------------------------------------=== #
|
||||
# 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 interior origins.
|
||||
#
|
||||
# ===----------------------------------------------------------------------=== #
|
||||
|
||||
# RUN: %parse-mojo-isolated %s -mlir-print-debuginfo | kgen-opt -lower-semantic-cf -check-lifetimes -verify-parameters -verify-diagnostics
|
||||
|
||||
def use_any[*Ts: AnyType](*args: *Ts): pass
|
||||
|
||||
# ===----------------------------------------------------------------------=== #
|
||||
# Test Type
|
||||
# ===----------------------------------------------------------------------=== #
|
||||
|
||||
struct MyList[T: AnyType](Movable where False):
|
||||
var data: UnsafePointer[Self.T, UntrackedOrigin[mut=True]]
|
||||
|
||||
def __init__(out self):
|
||||
self.data = UnsafePointer[Self.T, UntrackedOrigin[mut=True]].unsafe_dangling()
|
||||
|
||||
def __deinit__(deinit self):
|
||||
pass # Explicit deinit so it isn't considered trivial and elided.
|
||||
|
||||
def mutate(mut self): # must invalidate all interior origins.
|
||||
pass
|
||||
|
||||
def access(self): # doesn't invalidate interior origins.
|
||||
pass
|
||||
|
||||
@__unsafe_nested_origins_read_only
|
||||
def __getitem__(
|
||||
ref self
|
||||
) -> ref[self.data._get_ref_with_unsafe_interior_origin["element"](self)] Self.T:
|
||||
return self.data._get_ref_with_unsafe_interior_origin["element"](self)
|
||||
|
||||
# ===----------------------------------------------------------------------=== #
|
||||
# Basic Tests
|
||||
# ===----------------------------------------------------------------------=== #
|
||||
|
||||
def test_invalidate_base():
|
||||
# expected-note @+1 {{'list' declared here}}
|
||||
var list = MyList[Int]()
|
||||
|
||||
ref elt_ref1 = list[]
|
||||
elt_ref1 += 4
|
||||
list^.__deinit__()
|
||||
|
||||
# Deleting list obviously invalidates it.
|
||||
# expected-error @+1 {{use of uninitialized value 'list'}}
|
||||
elt_ref1 += 4
|
||||
|
||||
def test_invalidate_interior():
|
||||
var list = MyList[Int]()
|
||||
ref elt_ref2 = list[]
|
||||
elt_ref2 += 4
|
||||
list.mutate() # expected-note {{origin was invalidated here}}
|
||||
# expected-error @+1 {{use of invalidated interior reference 'list["element"]'}}
|
||||
elt_ref2 += 4
|
||||
|
||||
# simple control flow test.
|
||||
def test_if(cond: Bool):
|
||||
var list = MyList[Int]()
|
||||
ref elt_ref2 = list[]
|
||||
elt_ref2 += 4
|
||||
if cond:
|
||||
list.mutate() # expected-note {{origin was invalidated here}}
|
||||
# expected-error @+1 {{use of invalidated interior reference 'list["element"]'}}
|
||||
elt_ref2 += 4
|
||||
|
||||
struct TwoIntLists(Movable where False):
|
||||
var first: MyList[Int]
|
||||
var second: MyList[Int]
|
||||
|
||||
def __init__(out self):
|
||||
self.first = MyList[Int]()
|
||||
self.second = MyList[Int]()
|
||||
|
||||
# Test that we can handle nested field sensitivity correctly.
|
||||
def test_field_sensitive_nested_invalidation():
|
||||
var list_of_two_intlists = MyList[TwoIntLists]()
|
||||
ref first_list = list_of_two_intlists[].first
|
||||
ref second_list = list_of_two_intlists[].second
|
||||
|
||||
ref first_list_elt = first_list[]
|
||||
ref second_list_elt = second_list[]
|
||||
|
||||
# Mutating the elements of either list is fine, and shouldn't cause a
|
||||
# problem for anything.
|
||||
first_list_elt += 4
|
||||
second_list_elt += 4
|
||||
|
||||
# Mutating the first list shouldn't invalidate the second list because of
|
||||
# nested field sensitivity.
|
||||
first_list.mutate() # expected-note {{origin was invalidated here}}
|
||||
second_list_elt += 4
|
||||
|
||||
# However, it should invalidate the first list.
|
||||
# expected-error @+1 {{use of invalidated interior reference 'list_of_two_intlists["element"].first["element"]'}}
|
||||
first_list_elt += 4
|
||||
|
||||
def test_dominance_lifetime():
|
||||
var list = MyList[Int]()
|
||||
ref elt_ref2 = list[]
|
||||
elt_ref2 += 4 # This works
|
||||
list.mutate()
|
||||
|
||||
ref elt_ref3 = list[] # expected-note {{origin was defined here, after the reference was formed}}
|
||||
elt_ref3 += 4 # This works because the ref was refreshed.
|
||||
|
||||
# This is an error because the ref is invalidated.
|
||||
# expected-error @+1 {{use of invalidated interior reference 'list["element"]'}}
|
||||
elt_ref2 += 4
|
||||
|
||||
def test_dominance_lifetime2(cond: Bool):
|
||||
var list = MyList[Int]()
|
||||
ref elt_ref = list[]
|
||||
elt_ref += 4 # This works
|
||||
|
||||
# This is all fine, nothing invalidates elt_ref.
|
||||
var sum = 0
|
||||
if cond:
|
||||
sum += elt_ref
|
||||
list.access() # doesn't invalidate anything.
|
||||
else:
|
||||
sum += elt_ref
|
||||
sum += elt_ref
|
||||
|
||||
# This is not fine, because the list is mutated, potentially invalidating
|
||||
# elt_ref. It gets reinitialized within the body, but that doesn't make
|
||||
# elt_ref valid again!
|
||||
if cond: # expected-note {{origin was defined inside this control structure}}
|
||||
list.mutate()
|
||||
ref elt_ref_a = list[]
|
||||
elt_ref_a += 4 # This works because the ref was refreshed.
|
||||
else:
|
||||
list.mutate()
|
||||
ref elt_ref_b = list[]
|
||||
elt_ref_b += 4 # This works because the ref was refreshed.
|
||||
|
||||
# This is an error because the ref is invalidated.
|
||||
# expected-error @+1 {{use of invalidated interior reference 'list["element"]'}}
|
||||
elt_ref += 4
|
||||
|
||||
# This verifies we're handling hlcf.elif dominance correctly.
|
||||
def test_rederive_in_controlled_block(list: MyList[Int]) -> Int:
|
||||
if list[] > 0:
|
||||
return list[]
|
||||
return 0
|
||||
|
||||
def test_rederive_after_mutation_in_block(cond: Bool, mut list: MyList[Int]):
|
||||
ref r = list[]
|
||||
if cond:
|
||||
list.mutate() # expected-note {{origin was invalidated here}}
|
||||
# expected-error @+1 {{use of invalidated interior reference}}
|
||||
r += 1
|
||||
|
||||
# MOCO-4344 - Variadic packs + interior origins.
|
||||
def test_rederive_interior_in_variadic_pack(list: MyList[Int]):
|
||||
var n = 0
|
||||
ref k = n
|
||||
use_any(list[])
|
||||
use_any(k, list[])
|
||||
|
||||
# MOCO-4345 - vardecl store handling
|
||||
def test_vardecl_store_handling(list: MyList[Int]):
|
||||
var p: type_of(Pointer(to=list[]))
|
||||
p = Pointer(to=list[])
|
||||
_ = p
|
||||
|
||||
def test_bad_io_concrete[attr: StringLiteral](ptr: UnsafePointer[Int, _]) -> Int:
|
||||
var str = String()
|
||||
# expected-error @+1 {{interior origin name must be a string literal, it cannot be parametric when used}}
|
||||
ref r = ptr._get_ref_with_unsafe_interior_origin[attr](str)
|
||||
return r
|
||||
|
||||
def ret_invalid_ref(mut list: MyList[Int]) -> ref[list[]] Int:
|
||||
ref r = list[]
|
||||
list.mutate() # expected-note {{origin was invalidated here}}
|
||||
return r # expected-error {{use of invalidated interior reference 'list["element"]'}}
|
||||
|
||||
# This shouldn't crash.
|
||||
def test_thing1(data: MyList[String]) raises -> ref[data[]] String:
|
||||
return data[]
|
||||
def test_thing2(data: MyList[String]) raises -> ref[data[]] String:
|
||||
return test_thing1(data)
|
||||
|
||||
# This shouldn't crash.
|
||||
def throwing_function(ref values: MyList[String]) raises -> ref[values[]] String:
|
||||
return values[]
|
||||
|
||||
def call_throwing_fn(list: MyList[String]) raises:
|
||||
_ = throwing_function(list)
|
||||
|
||||
struct StructWithList(Movable where False):
|
||||
var data: MyList[String]
|
||||
|
||||
def add_type(mut self) -> ref[self.data[]] String:
|
||||
return self.data[]
|
||||
|
||||
def test_struct_with_list(var thing: StructWithList):
|
||||
_ = thing.add_type()
|
||||
|
||||
|
||||
struct KeyErr(ErrorConversionTrait):
|
||||
pass
|
||||
def access_or_raise_custom_error(a: MyList[Int])raises KeyErr -> ref[a[]] Int :
|
||||
return a[]
|
||||
|
||||
# MOCO-4371
|
||||
def test_access_or_raise_custom_error_convert_to_error() raises:
|
||||
var l = MyList[Int]()
|
||||
# This should be valid.
|
||||
var x = access_or_raise_custom_error(l)
|
||||
_ = x
|
||||
|
||||
# MOCO-4374
|
||||
def test_problem_4374():
|
||||
var lst = MyList[Int]()
|
||||
var p = Pointer(to=lst[])
|
||||
_ = p[]
|
||||
|
||||
# ===----------------------------------------------------------------------=== #
|
||||
# Closures
|
||||
# ===----------------------------------------------------------------------=== #
|
||||
|
||||
def test_nested_fn1():
|
||||
var base = MyList[Int]()
|
||||
var p = Pointer(to=base[])
|
||||
|
||||
@__copy_capture(p)
|
||||
@__parameter
|
||||
def inner():
|
||||
_ = p == p # Should be fine.
|
||||
inner()
|
||||
|
||||
def test_nested_fn2():
|
||||
var base = MyList[Int]()
|
||||
var p = Pointer(to=base[])
|
||||
|
||||
@__copy_capture(p)
|
||||
@__parameter
|
||||
def inner():
|
||||
_ = p == p # Should be fine.
|
||||
# expected-error @+1 {{incorrect invalidation of interior origin in closure 'base["element"]'}}
|
||||
base.mutate()
|
||||
inner()
|
||||
|
||||
def test_nested_fn3():
|
||||
var base = MyList[Int]()
|
||||
var p = Pointer(to=base[])
|
||||
|
||||
@__copy_capture(p)
|
||||
@__parameter
|
||||
def inner():
|
||||
_ = p == p # Should be fine.
|
||||
|
||||
base.mutate() # expected-note {{origin was invalidated here}}
|
||||
inner() # expected-error {{use of invalidated interior reference 'base["element"]'}}
|
||||
|
||||
def test_nested_fn4():
|
||||
var base = MyList[Int]()
|
||||
var p = Pointer(to=base[])
|
||||
|
||||
@__copy_capture(p)
|
||||
@__parameter
|
||||
def inner():
|
||||
_ = p == p # Should be fine.
|
||||
|
||||
base.mutate()
|
||||
_ = base[] # attempt to refresh.
|
||||
# FIXME: This should be an error; we should make sure we have the same
|
||||
# version of the reference as when the closure was created.
|
||||
inner()
|
||||
|
||||
def test_loop_iteration(var list: List[Int]):
|
||||
# The mutate method should invalidate the active iterator.
|
||||
# expected-error @+1 {{use of invalidated interior reference 'list["element"]'}}
|
||||
for _ in list:
|
||||
# expected-note @+1 {{origin was invalidated here}}
|
||||
list.append(4)
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,687 @@
|
||||
# ===----------------------------------------------------------------------=== #
|
||||
# Copyright (c) 2026, Modular Inc. All rights reserved.
|
||||
#
|
||||
# Licensed under the Apache License v2.0 with LLVM Exceptions:
|
||||
# https://llvm.org/LICENSE.txt
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
# ===----------------------------------------------------------------------=== #
|
||||
|
||||
# RUN: %parse-mojo-isolated %s --mlir-print-debuginfo -o %t.mlir
|
||||
# RUN: kgen-opt %t.mlir -lower-semantic-cf -check-lifetimes -verify-parameters -verify-diagnostics | FileCheck %s
|
||||
# RUN: %parse-mojo-isolated %s --mlir-print-debuginfo --debug-level full -o /dev/null
|
||||
|
||||
# Control flow related CheckLifetimes tests.
|
||||
|
||||
|
||||
def use(err: Error):
|
||||
pass
|
||||
|
||||
|
||||
def use(str: String):
|
||||
pass
|
||||
|
||||
|
||||
def use(a: MemExample):
|
||||
pass
|
||||
|
||||
|
||||
def use_mut(mut a: MemExample):
|
||||
pass
|
||||
|
||||
|
||||
# CHECK-LABEL: lit.struct.decl @MemExample
|
||||
struct MemExample(ImplicitlyCopyable):
|
||||
var x: Int
|
||||
|
||||
def __init__(out self):
|
||||
self.x = 42
|
||||
pass
|
||||
|
||||
def noop(self):
|
||||
pass
|
||||
|
||||
def __init__(out self, *, deinit move: Self):
|
||||
self.x = move.x
|
||||
|
||||
def __init__(out self, *, copy: Self):
|
||||
self.x = copy.x
|
||||
|
||||
def __bool__(self) -> Bool:
|
||||
return True
|
||||
|
||||
def unsafe_ptr(self) -> UnsafePointer[Int, AnyOrigin[mut=True]]:
|
||||
return UnsafePointer[Int, AnyOrigin[mut=True]].unsafe_dangling()
|
||||
|
||||
def __deinit__(deinit self):
|
||||
pass
|
||||
|
||||
|
||||
# CHECK-LABEL: lit.fn @"if_examples
|
||||
def if_examples(cond: __mlir_type.`!kgen.scalar<bool>`):
|
||||
# CHECK: %_a = lit.var.decl
|
||||
var _a: MemExample
|
||||
|
||||
# CHECK-NEXT: %_b = lit.var.decl
|
||||
# CHECK-NEXT: lifetime.start %_b
|
||||
# CHECK-NEXT: lit.call {{.*}}__init__{{.*}}(%_b)
|
||||
# CHECK-NEXT: lit.call {{.*}}__deinit__{{.*}}(%_b)
|
||||
# CHECK-NEXT: lifetime.end %_b
|
||||
var _b = MemExample()
|
||||
|
||||
# CHECK: hlcf.elif %cond {
|
||||
if cond:
|
||||
# CHECK-NEXT: lifetime.start %_a
|
||||
# CHECK-NEXT: lit.call {{.*}}__init__{{.*}}(%_a)
|
||||
# CHECK-NEXT: lit.call {{.*}}__deinit__{{.*}}(%_a)
|
||||
# CHECK-NEXT: lifetime.end %_a
|
||||
_a = MemExample()
|
||||
# CHECK-NEXT: hlcf.yield
|
||||
# CHECK-NEXT: } else {
|
||||
else:
|
||||
# CHECK-NEXT: lifetime.start %_b
|
||||
# CHECK-NEXT: lit.call {{.*}}__init__{{.*}}(%_b)
|
||||
# CHECK-NEXT: lit.call {{.*}}__deinit__{{.*}}(%_b)
|
||||
# CHECK-NEXT: lifetime.end %_b
|
||||
_b = MemExample()
|
||||
# CHECK-NEXT: hlcf.yield
|
||||
# CHECK-NEXT: }
|
||||
|
||||
# CHECK-NEXT: %c = lit.var.decl
|
||||
# CHECK-NEXT: lifetime.start %c
|
||||
# CHECK-NEXT: lit.call {{.*}}__init__{{.*}}(%c)
|
||||
var c = MemExample()
|
||||
# CHECK: hlcf.elif %cond {
|
||||
if cond:
|
||||
# CHECK-NEXT: lit.call {{.*}}__deinit__{{.*}}(%c)
|
||||
# CHECK-NEXT: lifetime.end %c
|
||||
# CHECK-NEXT: lifetime.start %c
|
||||
# CHECK-NEXT: lit.call {{.*}}__init__{{.*}}(%c)
|
||||
c = MemExample()
|
||||
# CHECK-NEXT: hlcf.yield
|
||||
# CHECK-NEXT: } else {
|
||||
else:
|
||||
pass
|
||||
# CHECK-NEXT: hlcf.yield
|
||||
# CHECK-NEXT: }
|
||||
# CHECK-NEXT: [[IMMREF:%.*]] = lit.ref.immut %c
|
||||
# CHECK-NEXT: lit.call {{.*}}noop{{.*}}([[IMMREF]])
|
||||
c.noop()
|
||||
# CHECK-NEXT: lit.call {{.*}}__deinit__{{.*}}(%c)
|
||||
# CHECK-NEXT: lifetime.end %c
|
||||
|
||||
# CHECK-NEXT: %d = lit.var.decl "d"
|
||||
# CHECK-NEXT: lifetime.start %d
|
||||
# CHECK-NEXT: lit.call {{.*}}__init__{{.*}}(%d)
|
||||
var d = MemExample()
|
||||
|
||||
# CHECK: [[ONE:%.+]] = kgen.param.constant: scalar<bool> = <true>
|
||||
# CHECK-NEXT: hlcf.elif [[ONE]] {
|
||||
# expected-warning @below {{'if' condition always evaluates to 'True'; 'else' branch is unreachable}}
|
||||
if True:
|
||||
# CHECK-NEXT: [[IMMREF:%.*]] = lit.ref.immut %d
|
||||
# CHECK-NEXT: lit.call {{.*}}noop{{.*}}([[IMMREF]])
|
||||
d.noop()
|
||||
# CHECK-NEXT: hlcf.yield
|
||||
# CHECK-NEXT: } else {
|
||||
# CHECK-NEXT: kgen.unreachable
|
||||
# CHECK-NEXT: }
|
||||
|
||||
# CHECK-NEXT: [[IMMREF:%.*]] = lit.ref.immut %d
|
||||
# CHECK-NEXT: lit.call {{.*}}noop{{.*}}([[IMMREF]])
|
||||
d.noop()
|
||||
# CHECK-NEXT: lit.call {{.*}}__deinit__{{.*}}(%d)
|
||||
# CHECK-NEXT: lifetime.end %d
|
||||
|
||||
|
||||
# CHECK-LABEL: lit.fn @"try_examples
|
||||
def try_examples(cond: __mlir_type.`!kgen.scalar<bool>`):
|
||||
# CHECK-NEXT: %a = lit.var.decl
|
||||
# CHECK-NEXT: %caught_error = lit.var.decl
|
||||
var a: MemExample
|
||||
# CHECK: lit.try "try0" {
|
||||
# CHECK-NOT: %a
|
||||
try:
|
||||
# The error value isn't used on the except branch, so it's copy from err
|
||||
# is completely optimized out.
|
||||
|
||||
# CHECK-NEXT: lit.var.lifetime.start %caught_error
|
||||
# CHECK-NEXT: lit.call {{.*}}@Error::@"__init__{{.*}}(%caught_error)
|
||||
# CHECK-NEXT: lit.try.raise
|
||||
raise Error()
|
||||
# CHECK: } except {
|
||||
except caught_error:
|
||||
# CHECK-NEXT: lifetime.start %a
|
||||
# CHECK-NEXT: lit.call {{.*}}__init__{{.*}}(%a)
|
||||
a = MemExample()
|
||||
# CHECK-NEXT: lit.ownership.use %caught_error
|
||||
# CHECK-NEXT: lit.ownership.use %caught_error
|
||||
_ = caught_error^
|
||||
# CHECK-NEXT: lit.call {{.*}}Error::@"__deinit__{{.*}}(%caught_error)
|
||||
# CHECK-NEXT: lit.var.lifetime.end %caught_error
|
||||
# CHECK-NEXT: lit.try.yield
|
||||
# CHECK-NEXT: } else {
|
||||
# CHECK-NEXT: kgen.unreachable
|
||||
# CHECK-NEXT: }
|
||||
# CHECK-NEXT: [[IMMREF:%.*]] = lit.ref.immut %a
|
||||
# CHECK-NEXT: lit.call {{.*}}noop{{.*}}([[IMMREF]])
|
||||
a.noop() # ok
|
||||
# CHECK-NEXT: lit.call {{.*}}__deinit__{{.*}}(%a)
|
||||
# CHECK-NEXT: lifetime.end %a
|
||||
|
||||
# CHECK-NEXT: %_b = lit.var.decl
|
||||
var _b: MemExample
|
||||
# CHECK-NEXT: [[ERRSLOT:%.*]] = lit.var.decl "e"
|
||||
# CHECK-NEXT: lit.try "{{.*}}" {
|
||||
try:
|
||||
# CHECK-NEXT: lifetime.start %_b
|
||||
# CHECK-NEXT: lit.call {{.*}}__init__{{.*}}(%_b)
|
||||
_b = MemExample()
|
||||
# CHECK-NEXT: lit.call {{.*}}__deinit__{{.*}}(%_b)
|
||||
# CHECK-NEXT: lifetime.end %_b
|
||||
raise Error()
|
||||
# CHECK: } except {
|
||||
# CHECK-NEXT: [[ERR:%.*]] = lit.ref.immut [[ERRSLOT]]
|
||||
# CHECK-NEXT: lit.call {{.*}}use{{.*}}([[ERR]])
|
||||
|
||||
# CHECK-NEXT: lit.call {{.*}}__deinit__{{.*}}([[ERRSLOT]])
|
||||
# CHECK-NEXT: lit.var.lifetime.end [[ERRSLOT]]
|
||||
# CHECK-NEXT: lit.try.yield
|
||||
except e:
|
||||
use(e)
|
||||
# CHECK-NEXT: } else {
|
||||
# CHECK-NEXT: kgen.unreachable
|
||||
# CHECK-NEXT: }
|
||||
|
||||
# CHECK-NEXT: lifetime.start %_b
|
||||
# CHECK-NEXT: lit.call {{.*}}__init__{{.*}}(%_b)
|
||||
_b = MemExample()
|
||||
# CHECK-NEXT: lit.call {{.*}}__deinit__{{.*}}(%_b)
|
||||
# CHECK-NEXT: lifetime.end %_b
|
||||
|
||||
# CHECK-NEXT: %c = lit.var.decl
|
||||
var c: MemExample
|
||||
# CHECK-NEXT: [[ERRSLOT:%.*]] = lit.var.decl "e"
|
||||
# CHECK-NEXT: lit.try "{{.*}}" {
|
||||
try:
|
||||
# CHECK-NEXT: lifetime.start %c
|
||||
# CHECK-NEXT: lit.call {{.*}}__init__{{.*}}(%c)
|
||||
c = MemExample()
|
||||
# CHECK-NOT: %c
|
||||
raise Error()
|
||||
# CHECK: } except {
|
||||
# CHECK-NEXT: [[ERR:%.*]] = lit.ref.immut [[ERRSLOT]]
|
||||
# CHECK-NEXT: lit.call {{.*}}use{{.*}}([[ERR]])
|
||||
|
||||
# CHECK-NEXT: lit.call {{.*}}__deinit__{{.*}}([[ERRSLOT]])
|
||||
# CHECK-NEXT: lifetime.end [[ERRSLOT]]
|
||||
|
||||
# CHECK-NEXT: lit.try.yield
|
||||
except e:
|
||||
use(e)
|
||||
# CHECK-NEXT: } else {
|
||||
# CHECK-NEXT: kgen.unreachable
|
||||
# CHECK-NEXT: }
|
||||
# CHECK-NEXT: [[IMMREF:%.*]] = lit.ref.immut %c
|
||||
# CHECK-NEXT: lit.call {{.*}}noop{{.*}}([[IMMREF]])
|
||||
c.noop()
|
||||
# CHECK-NEXT: lit.call {{.*}}__deinit__{{.*}}(%c)
|
||||
# CHECK-NEXT: lifetime.end %c
|
||||
|
||||
# CHECK-NEXT: %d = lit.var.decl
|
||||
var d: MemExample
|
||||
# CHECK-NEXT: [[ERRSLOT:%.*]] = lit.var.decl "e"
|
||||
# CHECK-NEXT: lit.try "{{.*}}" {
|
||||
try:
|
||||
# CHECK-NEXT: hlcf.elif %cond {
|
||||
if cond:
|
||||
raise Error()
|
||||
# CHECK-NOT: %d
|
||||
# CHECK: } except {
|
||||
except e:
|
||||
# CHECK: call {{.*}}Error::@"__deinit__
|
||||
use(e)
|
||||
# CHECK: lit.call {{.*}}__init__{{.*}}(%d)
|
||||
d = MemExample()
|
||||
# CHECK-NEXT: lit.try.yield
|
||||
# CHECK-NEXT: } else {
|
||||
else:
|
||||
# CHECK-NEXT: lifetime.start %d
|
||||
# CHECK-NEXT: lit.call {{.*}}__init__{{.*}}(%d)
|
||||
d = MemExample()
|
||||
# CHECK-NEXT: lit.try.yield
|
||||
# CHECK-NEXT: }
|
||||
|
||||
# CHECK-NEXT: [[IMMREF:%.*]] = lit.ref.immut %d
|
||||
# CHECK-NEXT: lit.call {{.*}}noop{{.*}}([[IMMREF]])
|
||||
d.noop()
|
||||
# CHECK-NEXT: lit.call {{.*}}__deinit__{{.*}}(%d)
|
||||
# CHECK-NEXT: lifetime.end %d
|
||||
|
||||
|
||||
# CHECK-LABEL: lit.fn @"chris_origin_example
|
||||
def chris_origin_example(a: Bool, b: Bool):
|
||||
var x: MemExample
|
||||
# CHECK: lit.try
|
||||
try:
|
||||
# CHECK: lit.try
|
||||
try:
|
||||
# CHECK: hlcf.elif
|
||||
if a:
|
||||
# CHECK: __init__{{.*}}(%x)
|
||||
x = MemExample()
|
||||
|
||||
# CHECK: lit.try.raise
|
||||
raise Error()
|
||||
# CHECK: except
|
||||
# CHECK: lit.call {{.*}}__mlir_bool__
|
||||
# CHECK-NEXT: hlcf.elif %{{.*}} {
|
||||
# CHECK-NEXT: __deinit__{{.*}}(%x)
|
||||
# CHECK: return
|
||||
# CHECK: else
|
||||
# CHECK: lit.try.raise
|
||||
# CHECK: else
|
||||
# CHECK: hlcf.elif
|
||||
# CHECK: return
|
||||
# CHECK: else
|
||||
finally:
|
||||
if b:
|
||||
return
|
||||
# CHECK: } except {
|
||||
# CHECK: } except {
|
||||
except:
|
||||
# CHECK: lit.call {{.*}}@"use_mut{{.*}}(%x)
|
||||
# CHECK: lit.call {{.*}}__deinit__{{.*}}(%x)
|
||||
use_mut(x)
|
||||
# CHECK: else
|
||||
# CHECK-NEXT: lit.try.yield
|
||||
|
||||
|
||||
# CHECK-LABEL: lit.fn @"loop_example
|
||||
def loop_example(cond1: __mlir_type.`!kgen.scalar<bool>`, cond2: __mlir_type.`!kgen.scalar<bool>`):
|
||||
# CHECK-NEXT: %a = lit.var.decl "a"
|
||||
var a: MemExample
|
||||
# CHECK-NEXT: %b = lit.var.decl "b"
|
||||
var b: MemExample
|
||||
# CHECK-NEXT: %c = lit.var.decl "c"
|
||||
var c: MemExample
|
||||
|
||||
# CHECK-NEXT: lifetime.start %a
|
||||
# CHECK-NEXT: lit.call {{.*}}__init__{{.*}}(%a)
|
||||
a = MemExample()
|
||||
|
||||
# Unneeded boilerplate due to 'while True':
|
||||
# CHECK-NEXT: hlcf.loop "_loop_0" {
|
||||
# CHECK-NEXT: = kgen.param.constant: scalar<bool> = <true>
|
||||
# CHECK-NEXT: hlcf.elif
|
||||
# CHECK-NEXT: hlcf.yield
|
||||
# CHECK-NEXT: } else {
|
||||
# CHECK-NEXT: kgen.unreachable
|
||||
# CHECK-NEXT: }
|
||||
while True:
|
||||
# CHECK-NEXT: lifetime.start %c
|
||||
# CHECK-NEXT: lit.call {{.*}}__init__{{.*}}(%c)
|
||||
c = MemExample()
|
||||
# CHECK-NEXT: hlcf.elif %cond2 {
|
||||
if cond2:
|
||||
# CHECK-NEXT: lifetime.start %b
|
||||
# CHECK-NEXT: lit.call {{.*}}__init__{{.*}}(%b)
|
||||
b = MemExample()
|
||||
# CHECK-NEXT: hlcf.break
|
||||
break
|
||||
# CHECK-NEXT: } else {
|
||||
# CHECK-NEXT: lit.call {{.*}}__deinit__{{.*}}(%c)
|
||||
# CHECK-NEXT: lifetime.end %c
|
||||
# CHECK-NEXT: lit.call {{.*}}__deinit__{{.*}}(%a)
|
||||
# CHECK-NEXT: lifetime.end %a
|
||||
# CHECK-NEXT: hlcf.yield
|
||||
# CHECK-NEXT: }
|
||||
|
||||
# CHECK-NEXT: lifetime.start %a
|
||||
# CHECK-NEXT: lit.call {{.*}}__init__{{.*}}(%a)
|
||||
# CHECK-NEXT: hlcf.continue
|
||||
a = MemExample()
|
||||
# CHECK-NEXT: }
|
||||
|
||||
# CHECK-NEXT: [[IMMREF:%.*]] = lit.ref.immut %a
|
||||
# CHECK-NEXT: lit.call {{.*}}noop{{.*}}([[IMMREF]])
|
||||
a.noop()
|
||||
# CHECK-NEXT: lit.call {{.*}}__deinit__{{.*}}(%a)
|
||||
# CHECK-NEXT: lifetime.end %a
|
||||
|
||||
# CHECK-NEXT: [[IMMREF:%.*]] = lit.ref.immut %b
|
||||
# CHECK-NEXT: lit.call {{.*}}noop{{.*}}([[IMMREF]])
|
||||
b.noop()
|
||||
# CHECK-NEXT: lit.call {{.*}}__deinit__{{.*}}(%b)
|
||||
# CHECK-NEXT: lifetime.end %b
|
||||
|
||||
# CHECK-NEXT: [[IMMREF:%.*]] = lit.ref.immut %c
|
||||
# CHECK-NEXT: lit.call {{.*}}noop{{.*}}([[IMMREF]])
|
||||
c.noop()
|
||||
# CHECK-NEXT: lit.call {{.*}}__deinit__{{.*}}(%c)
|
||||
# CHECK-NEXT: lifetime.end %c
|
||||
|
||||
|
||||
# CHECK-LABEL: lit.struct.decl @TestLoopWithWholeObjectBit
|
||||
struct TestLoopWithWholeObjectBit(Movable where False):
|
||||
var field: MemExample
|
||||
|
||||
# CHECK: lit.fn @"__init__
|
||||
@implicit
|
||||
def __init__(out self, cond: __mlir_type.`!kgen.scalar<bool>`):
|
||||
# CHECK-NEXT: %buf = lit.var.decl "buf"
|
||||
# CHECK-NEXT: lifetime.start %buf
|
||||
# CHECK-NEXT: lit.call {{.*}}__init__{{.*}}(%buf)
|
||||
var buf = MemExample()
|
||||
|
||||
# CHECK-NEXT: hlcf.loop "_loop_0" {
|
||||
# CHECK-NEXT: hlcf.elif %cond {
|
||||
# CHECK-NEXT: hlcf.yield
|
||||
# CHECK-NEXT: } else {
|
||||
# CHECK-NEXT: hlcf.break
|
||||
# CHECK-NEXT: }
|
||||
while cond:
|
||||
# CHECK-NEXT: [[IMMREF:%.*]] = lit.ref.immut %buf
|
||||
# CHECK-NEXT: lit.call {{.*}}noop{{.*}}([[IMMREF]])
|
||||
# CHECK-NEXT: hlcf.continue
|
||||
buf.noop()
|
||||
# CHECK-NEXT: }
|
||||
|
||||
# CHECK-NEXT: [[FIELD_REF:%.*]] = lit.ref.struct.ger %self[field]
|
||||
# CHECK-NEXT: lit.ownership.use %buf
|
||||
# CHECK-NEXT: lit.call {{.*}}__init__{{.*}}move"
|
||||
# CHECK-NEXT: lifetime.end %buf
|
||||
# CHECK-NEXT: %none = kgen.param.constant
|
||||
# CHECK-NEXT: kgen.return
|
||||
self.field = buf^
|
||||
|
||||
|
||||
# CHECK-LABEL: lit.fn @"testInfiniteloop
|
||||
def testInfiniteloop():
|
||||
# CHECK-NEXT: hlcf.loop "_loop_0" {
|
||||
# CHECK-NEXT: [[T:%.+]] = kgen.param.constant: scalar<bool> = <true>
|
||||
# CHECK-NEXT: hlcf.elif [[T]] {
|
||||
# CHECK-NEXT: hlcf.yield
|
||||
# CHECK-NEXT: } else {
|
||||
# CHECK-NEXT: kgen.unreachable
|
||||
# CHECK-NEXT: }
|
||||
while True:
|
||||
# CHECK-NEXT: %localThing = lit.var.decl
|
||||
# CHECK-NEXT: lifetime.start %localThing
|
||||
# CHECK-NEXT: lit.call {{.*}}__init__{{.*}}(%localThing)
|
||||
# CHECK-NEXT: [[IMMREF:%.*]] = lit.ref.immut %localThing
|
||||
# CHECK-NEXT: lit.call {{.*}}noop{{.*}}([[IMMREF]])
|
||||
# CHECK-NEXT: lit.call {{.*}}__deinit__{{.*}}(%localThing)
|
||||
# CHECK-NEXT: lifetime.end %localThing
|
||||
var localThing = MemExample()
|
||||
localThing.noop()
|
||||
# CHECK-NEXT: hlcf.continue
|
||||
# CHECK-NEXT: }
|
||||
|
||||
|
||||
@fieldwise_init
|
||||
struct TrivialRange(Iterator, TrivialRegisterPassable):
|
||||
comptime Element = Int
|
||||
|
||||
def __iter__(self) -> Self:
|
||||
return self
|
||||
|
||||
def __next__(mut self) raises StopIteration -> Int:
|
||||
if self.__len__() > 0:
|
||||
return 1
|
||||
else:
|
||||
raise StopIteration()
|
||||
|
||||
def __len__(self) -> Int:
|
||||
return 1
|
||||
|
||||
|
||||
# Issue #98: https://github.com/modular/mojo/issues/98
|
||||
# CHECK-LABEL: lit.fn @"mojo98
|
||||
def mojo98(n: Int):
|
||||
var a = MemExample()
|
||||
for i in TrivialRange():
|
||||
a.x = i
|
||||
|
||||
|
||||
struct MyStringReturningCtx(Movable):
|
||||
var s: String
|
||||
|
||||
def __init__(out self):
|
||||
self.s = "hey"
|
||||
|
||||
def __enter__(var self) -> Self:
|
||||
return self^
|
||||
|
||||
def __init__(out self, *, deinit move: Self):
|
||||
self.s = ""
|
||||
|
||||
def read(self) raises -> String:
|
||||
return ""
|
||||
|
||||
|
||||
# CHECK-LABEL: lit.fn @"testErrorReturn
|
||||
def testErrorReturn() raises:
|
||||
var input: String
|
||||
# CHECK: try
|
||||
with MyStringReturningCtx() as ctx:
|
||||
# CHECK-NOT: @MyStringReturningCtx::@"__deinit__
|
||||
var x = ctx.read()
|
||||
input = "hello"
|
||||
# CHECK: except
|
||||
use(input)
|
||||
|
||||
|
||||
def marker():
|
||||
pass
|
||||
|
||||
|
||||
# CHECK-LABEL: lit.fn @"test_param_for1
|
||||
# MOCO-831
|
||||
def test_param_for1(cond: Bool, cond2: Bool):
|
||||
# CHECK-NEXT: %mem = lit.var.decl
|
||||
# CHECK-NEXT: lifetime.start %mem
|
||||
# CHECK-NEXT: lit.call {{.*}}__init__{{.*}}(%mem)
|
||||
var mem = MemExample()
|
||||
|
||||
# CHECK: kgen.param.for [[ITER:[*].*]]: !TrivialRange in
|
||||
# CHECK-NEXT: has_next
|
||||
# CHECK-NEXT: get_next_iter
|
||||
# CHECK-SAME: {
|
||||
comptime for x in TrivialRange():
|
||||
# CHECK-NEXT: kgen.param.if {{.*}}paramfor_has_next
|
||||
|
||||
# Make sure nothing sneaks in here.
|
||||
# CHECK-NEXT: lit.call {{.*}}marker()
|
||||
marker()
|
||||
|
||||
# CHECK-NEXT: lit.call {{.*}}__mlir_bool__
|
||||
# CHECK-NEXT: hlcf.elif %{{.*}} {
|
||||
if cond:
|
||||
# CHECK: lit.call {{.*}}__deinit__{{.*}}(%mem)
|
||||
# CHECK-NEXT: lifetime.end %mem
|
||||
# CHECK-NEXT: lit.call {{.*}}marker()
|
||||
marker()
|
||||
# CHECK-NEXT: kgen.param.for.break
|
||||
break
|
||||
|
||||
# CHECK: hlcf.elif %{{.*}} {
|
||||
if cond2:
|
||||
# CHECK: lit.call {{.*}}__deinit__{{.*}}(%mem)
|
||||
# CHECK-NEXT: lifetime.end %mem
|
||||
# CHECK-NEXT: lit.call {{.*}}marker()
|
||||
marker()
|
||||
# CHECK-NEXT: kgen.param.for.break
|
||||
break
|
||||
# CHECK-NEXT: } else {
|
||||
# CHECK-NEXT: hlcf.yield
|
||||
# CHECK-NEXT: }
|
||||
# CHECK-NEXT: lit.call {{.*}}marker()
|
||||
marker()
|
||||
# CHECK-NEXT: kgen.param.for.continue
|
||||
|
||||
# This is the else from the param.if inside the param.for.
|
||||
# CHECK-NEXT: } else {
|
||||
else:
|
||||
# CHECK-NEXT: [[TMP:%.*]] = lit.ref.immut %mem
|
||||
# CHECK-NEXT: lit.call {{.*}}use{{.*}}([[TMP]])
|
||||
use(mem)
|
||||
# CHECK: lit.call {{.*}}__deinit__{{.*}}(%mem)
|
||||
# CHECK-NEXT: lifetime.end %mem
|
||||
|
||||
# CHECK-NEXT: lit.call {{.*}}marker()
|
||||
marker()
|
||||
# CHECK-NEXT: kgen.param.for.break
|
||||
# Finish out the param.if and the param.for
|
||||
# CHECK-NEXT: } {elseIsolated, thenIsolated}
|
||||
# CHECK-NEXT: kgen.unreachable
|
||||
# CHECK-NEXT: } else {
|
||||
# CHECK-NEXT: kgen.unreachable
|
||||
# CHECK-NEXT: } {bodyIsolated, elseIsolated}
|
||||
|
||||
|
||||
# CHECK-LABEL: lit.fn @"test_param_for2
|
||||
# MOCO-831
|
||||
def test_param_for2():
|
||||
# CHECK: lit.call {{.*}}__init__{{.*}}(%mem)
|
||||
var mem = MemExample()
|
||||
|
||||
# CHECK: kgen.param.for [[ITER:[*].*]]: !TrivialRange in
|
||||
# CHECK-NEXT: has_next
|
||||
# CHECK-NEXT: get_next_iter
|
||||
# CHECK-SAME: {
|
||||
comptime for x in TrivialRange():
|
||||
# CHECK-NEXT: kgen.param.if {{.*}}paramfor_has_next
|
||||
|
||||
# Make sure nothing sneaks in here.
|
||||
# CHECK-NEXT: lit.call {{.*}}marker()
|
||||
marker()
|
||||
|
||||
# CHECK-NEXT: lit.call {{.*}}use_mut{{.*}}(%mem)
|
||||
use_mut(mem)
|
||||
# CHECK-NEXT: kgen.param.for.continue
|
||||
|
||||
# CHECK-NEXT: } else {
|
||||
else:
|
||||
# CHECK-NEXT: lit.call {{.*}}__deinit__{{.*}}(%mem)
|
||||
# CHECK-NEXT: lifetime.end %mem
|
||||
# CHECK-NEXT: lit.call {{.*}}marker()
|
||||
marker()
|
||||
|
||||
# CHECK-NEXT: kgen.param.for.break
|
||||
|
||||
|
||||
# CHECK-LABEL: lit.fn @"test_elif
|
||||
def test_elif(cond: Bool, cond2: Bool):
|
||||
var mem1 = MemExample()
|
||||
var mem2 = MemExample()
|
||||
var mem3 = MemExample()
|
||||
|
||||
# CHECK: __mlir_bool__
|
||||
# CHECK-NEXT: hlcf.elif %{{.*}} {
|
||||
if cond:
|
||||
# CHECK-NEXT: lit.call {{.*}}__deinit__{{.*}}(%mem3)
|
||||
# CHECK-NEXT: lifetime.end %mem3
|
||||
# CHECK-NEXT: lit.call {{.*}}__deinit__{{.*}}(%mem2)
|
||||
# CHECK-NEXT: lifetime.end %mem2
|
||||
# CHECK-NEXT: lit.call {{.*}}use_mut{{.*}}(%mem1)
|
||||
use_mut(mem1)
|
||||
# CHECK-NEXT: lit.call {{.*}}__deinit__{{.*}}(%mem1)
|
||||
# CHECK-NEXT: lifetime.end %mem1
|
||||
|
||||
# CHECK-NEXT: lit.call {{.*}}marker()
|
||||
marker()
|
||||
# CHECK-NEXT: hlcf.yield
|
||||
# CHECK-NEXT: } else {
|
||||
# mem1 never used at this point, destroy in the condition.
|
||||
# CHECK-NEXT: lit.call {{.*}}__deinit__{{.*}}(%mem1)
|
||||
# CHECK-NEXT: lifetime.end %mem1
|
||||
# CHECK-NEXT: __mlir_bool__
|
||||
# CHECK-NEXT: hlcf.elif.yield
|
||||
|
||||
# CHECK-NEXT: } then {
|
||||
elif cond2:
|
||||
# CHECK-NEXT: lit.call {{.*}}__deinit__{{.*}}(%mem3)
|
||||
# CHECK-NEXT: lifetime.end %mem3
|
||||
# CHECK-NEXT: lit.call {{.*}}__deinit__{{.*}}(%mem2)
|
||||
# CHECK-NEXT: lifetime.end %mem2
|
||||
|
||||
# CHECK-NEXT: lit.call {{.*}}marker()
|
||||
marker()
|
||||
# CHECK-NEXT: hlcf.yield
|
||||
# CHECK-NEXT: } else {
|
||||
|
||||
# Last use of mem2 is in this condition.
|
||||
# CHECK-NEXT: lit.ref.struct.ger %mem2[x]
|
||||
# CHECK-NEXT: kgen.rebind
|
||||
# CHECK-NEXT: lit.ref.load
|
||||
# CHECK-NEXT: lit.call {{.*}}__deinit__{{.*}}(%mem2)
|
||||
# CHECK: hlcf.elif.yield
|
||||
|
||||
# CHECK-NEXT: } then {
|
||||
elif mem2.x == 0:
|
||||
# CHECK-NEXT: lit.call {{.*}}use_mut{{.*}}(%mem3)
|
||||
use_mut(mem3)
|
||||
# CHECK-NEXT: lit.call {{.*}}__deinit__{{.*}}(%mem3)
|
||||
# CHECK-NEXT: lifetime.end %mem3
|
||||
|
||||
# CHECK-NEXT: lit.call {{.*}}marker()
|
||||
marker()
|
||||
# CHECK-NEXT: hlcf.yield
|
||||
|
||||
# CHECK-NEXT: } else {
|
||||
# CHECK-NEXT: lit.call {{.*}}__deinit__{{.*}}(%mem3)
|
||||
# CHECK-NEXT: lifetime.end %mem3
|
||||
# CHECK-NEXT: hlcf.yield
|
||||
|
||||
|
||||
# https://github.com/modular/mojo/issues/3710
|
||||
# Mojo frees memory while reference to it is still in use
|
||||
# CHECK-LABEL: lit.fn @"loop_any_origin
|
||||
def loop_any_origin(var mem: MemExample, cond: Bool):
|
||||
# CHECK: lit.call {{.*}}unsafe_ptr
|
||||
var ptr = mem.unsafe_ptr()
|
||||
|
||||
# The "mem" destructor must be in the loop exit, not ahead of the loop because
|
||||
# there is an access through AnyOrigin within the loop.
|
||||
# CHECK: hlcf.loop
|
||||
# CHECK-NEXT: lit.call {{.*}}Bool::@"__mlir_bool__
|
||||
# CHECK-NEXT: hlcf.elif
|
||||
# CHECK-NEXT: hlcf.yield
|
||||
# CHECK-NEXT: } else {
|
||||
# CHECK-NEXT: lit.call {{.*}}MemExample::@"__deinit__
|
||||
# CHECK-NEXT: lit.var.lifetime.end %ptr
|
||||
# CHECK-NEXT: hlcf.break
|
||||
while cond:
|
||||
ptr[] = 4
|
||||
|
||||
|
||||
# 4694: or/and handling of comparisons on PythonObject
|
||||
struct PyObjLike(RegisterPassable):
|
||||
def __init__(out self, *, copy: Self):
|
||||
pass
|
||||
|
||||
def __eq__(self, other: Self) raises -> Self:
|
||||
while True:
|
||||
pass
|
||||
|
||||
def __bool__(self) raises -> Bool:
|
||||
return True
|
||||
|
||||
def __deinit__(deinit self):
|
||||
pass
|
||||
|
||||
|
||||
# CHECK-LABEL: lit.fn @"test4694
|
||||
def test4694(a: PyObjLike, b: PyObjLike) raises:
|
||||
# Just check that we don't get a verifier error.
|
||||
if a == b or b == a:
|
||||
gotit()
|
||||
|
||||
|
||||
def gotit():
|
||||
pass
|
||||
@@ -0,0 +1,820 @@
|
||||
# ===----------------------------------------------------------------------=== #
|
||||
# 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.
|
||||
# ===----------------------------------------------------------------------=== #
|
||||
|
||||
# RUN: %parse-mojo-isolated %s -mlir-print-debuginfo | kgen-opt -lower-semantic-cf -check-lifetimes -verify-parameters -verify-diagnostics
|
||||
|
||||
def use(x: Some[AnyType]):
|
||||
pass
|
||||
|
||||
struct Empty(ImplicitlyCopyable):
|
||||
def __init__(out self):
|
||||
pass
|
||||
|
||||
|
||||
struct MemExample(ImplicitlyCopyable):
|
||||
var x: Int
|
||||
var y: Int
|
||||
|
||||
# expected-error @+1 {{'self.x' is uninitialized at the implicit return from this function}}
|
||||
def __init__(out self): # expected-note {{'self' declared here}}
|
||||
pass
|
||||
|
||||
# expected-error @+1 {{'self.y' is uninitialized at the implicit return from this function}}
|
||||
def __init__(
|
||||
out self, *, copy: Self # expected-note {{'self' declared here}}
|
||||
):
|
||||
self.x = copy.x
|
||||
|
||||
def noop(self):
|
||||
pass
|
||||
|
||||
def consume(var self):
|
||||
pass
|
||||
|
||||
def __deinit__(deinit self):
|
||||
pass
|
||||
|
||||
|
||||
struct RegExample(ImplicitlyCopyable, RegisterPassable):
|
||||
var regstate: Int
|
||||
|
||||
def __init__(out self):
|
||||
self.regstate = 1
|
||||
|
||||
def __init__(out self, *, copy: Self):
|
||||
self.regstate = 12
|
||||
|
||||
def __deinit__(deinit self):
|
||||
pass
|
||||
|
||||
def consume(var self):
|
||||
pass
|
||||
|
||||
|
||||
def use(x: RegExample):
|
||||
pass
|
||||
|
||||
|
||||
##===----------------------------------------------------------------------===##
|
||||
# Simple cases.
|
||||
##===----------------------------------------------------------------------===##
|
||||
|
||||
|
||||
def use_of_empty() -> Empty:
|
||||
var a: Empty # expected-note {{'a' declared here}}
|
||||
return a # expected-error {{use of uninitialized value 'a'}}
|
||||
|
||||
|
||||
def use_of_init() -> RegExample:
|
||||
var a = RegExample()
|
||||
return a # OK!
|
||||
|
||||
|
||||
def use_of_init2() -> MemExample:
|
||||
var a = MemExample()
|
||||
return a # OK!
|
||||
|
||||
|
||||
def use_of_uninit() -> RegExample:
|
||||
var a: RegExample # expected-note {{'a' declared here}}
|
||||
return a # expected-error {{use of uninitialized value 'a'}}
|
||||
|
||||
|
||||
def use_of_uninit2() -> MemExample:
|
||||
var a: MemExample # expected-note {{'a' declared here}}
|
||||
return a # expected-error {{use of uninitialized value 'a'}}
|
||||
|
||||
|
||||
def invalid_partial_init() -> MemExample:
|
||||
var a: MemExample # expected-note {{'a' declared here}}
|
||||
a.x = 42
|
||||
a.y = 42
|
||||
return a # expected-error {{'a' used with all fields manually initialized but without calling an '__init__' method}}
|
||||
|
||||
|
||||
def field_sensitive():
|
||||
var a: MemExample # expected-note {{'a' declared here}}
|
||||
a.x = 1
|
||||
use(a) # expected-error {{use of uninitialized value 'a.y'}}
|
||||
|
||||
var b = MemExample()
|
||||
b.x = 1
|
||||
b.y = 2
|
||||
use(b) # Ok
|
||||
|
||||
|
||||
# Issue #12859, bad location info
|
||||
def take_int(a: Int):
|
||||
pass
|
||||
|
||||
|
||||
def uninit_lvalue_int():
|
||||
var x: Int # expected-note {{'x' declared here}}
|
||||
take_int(x) # expected-error {{use of uninitialized value 'x'}}
|
||||
|
||||
|
||||
# Return-specific errors.
|
||||
def return_error1(mut a: MemExample): # expected-note {{'a' declared here}}
|
||||
a^.consume()
|
||||
return # expected-error {{'a' is uninitialized at return from this function}}
|
||||
|
||||
|
||||
# expected-error @+1 {{'a' is uninitialized at the implicit return from this function}}
|
||||
def return_error2(mut a: RegExample): # expected-note {{'a' declared here}}
|
||||
a^.consume()
|
||||
|
||||
|
||||
##===----------------------------------------------------------------------===##
|
||||
# Control flow
|
||||
##===----------------------------------------------------------------------===##
|
||||
|
||||
|
||||
def use_of_uninit_if(cond: Bool):
|
||||
var a: MemExample
|
||||
if cond:
|
||||
a = MemExample()
|
||||
else:
|
||||
a = MemExample()
|
||||
use(a) # Ok
|
||||
|
||||
var b: MemExample # expected-note {{'b' declared here}}
|
||||
if cond:
|
||||
b = MemExample()
|
||||
use(b) # expected-error {{use of uninitialized value 'b'}}
|
||||
|
||||
var c: MemExample
|
||||
if True:
|
||||
c = MemExample()
|
||||
use(c) # Ok due to the "if True:".
|
||||
|
||||
|
||||
def use_of_uninit_while(cond: Bool):
|
||||
var a: MemExample
|
||||
if cond:
|
||||
# Infinite loop never returns
|
||||
while True:
|
||||
pass
|
||||
else:
|
||||
a = MemExample()
|
||||
use(a) # Ok
|
||||
|
||||
var b: RegExample # expected-note {{'b' declared here}}
|
||||
while cond:
|
||||
b = RegExample()
|
||||
|
||||
use(b) # expected-error {{use of uninitialized value 'b'}}
|
||||
|
||||
|
||||
def use_of_uninit_raise(cond: Bool):
|
||||
var a: MemExample
|
||||
try:
|
||||
raise Error()
|
||||
except:
|
||||
a = MemExample()
|
||||
pass
|
||||
use(a) # ok
|
||||
|
||||
var b: MemExample
|
||||
try:
|
||||
b = MemExample()
|
||||
raise Error()
|
||||
except:
|
||||
pass
|
||||
use(b) # ok
|
||||
|
||||
var c: MemExample # expected-note {{'c' declared here}}
|
||||
try:
|
||||
if cond:
|
||||
c = MemExample()
|
||||
raise Error()
|
||||
else:
|
||||
raise Error()
|
||||
except:
|
||||
pass
|
||||
use(c) # expected-error {{use of uninitialized value 'c'}}
|
||||
|
||||
var d: MemExample
|
||||
try:
|
||||
if cond:
|
||||
raise Error()
|
||||
except:
|
||||
d = MemExample()
|
||||
else:
|
||||
d = MemExample()
|
||||
use(d) # Ok
|
||||
|
||||
|
||||
def may_raise() raises -> MemExample:
|
||||
return MemExample()
|
||||
|
||||
|
||||
def reassign_might_raise():
|
||||
var value = MemExample()
|
||||
try:
|
||||
# 'value' is passed directly as the MLValue slot to the raising call,
|
||||
# meaning the current value has to be destroyed before the call.
|
||||
value = may_raise()
|
||||
_ = value
|
||||
except:
|
||||
# If the call raises, then the value is known to be uninitialized.
|
||||
_ = value
|
||||
|
||||
|
||||
# expected-note @below {{'out' declared here}}
|
||||
def uninitialized_result(c: Bool, out out: MemExample):
|
||||
if c:
|
||||
# expected-error @below {{'out' is uninitialized at return from this function}}
|
||||
return
|
||||
out = MemExample()
|
||||
|
||||
|
||||
def test_unreachable_after_abort():
|
||||
abort()
|
||||
# expected-warning @+1 {{unreachable code after function that never returns}}
|
||||
var x = 4 + 5
|
||||
|
||||
|
||||
@no_inline
|
||||
def throwonly() raises -> Never:
|
||||
abort()
|
||||
|
||||
|
||||
def test_unreachable_after_throwonly() raises:
|
||||
throwonly()
|
||||
# expected-warning @+1 {{unreachable code after function that never returns}}
|
||||
var x = 4 + 5
|
||||
|
||||
|
||||
def test_unreachable_after_comptime_assert_false():
|
||||
comptime assert False
|
||||
# expected-warning @+1 {{unreachable code after compile-time assertion failure}}
|
||||
return
|
||||
|
||||
|
||||
##===----------------------------------------------------------------------===##
|
||||
# Complex aggregates
|
||||
##===----------------------------------------------------------------------===##
|
||||
|
||||
|
||||
struct TwoRegs(ImplicitlyCopyable):
|
||||
var reg1: RegExample
|
||||
var reg2: RegExample
|
||||
|
||||
def __init__(out self):
|
||||
self.reg1 = RegExample()
|
||||
self.reg2 = RegExample()
|
||||
|
||||
|
||||
struct TwoRegsRP(Copyable, RegisterPassable):
|
||||
var reg1: RegExample
|
||||
var reg2: RegExample
|
||||
|
||||
def __init__(out self):
|
||||
self.reg1 = RegExample()
|
||||
self.reg2 = RegExample()
|
||||
|
||||
|
||||
struct MoreComplexExample(ImplicitlyCopyable):
|
||||
var mem: MemExample
|
||||
var reg: TwoRegs
|
||||
|
||||
def __init__(out self):
|
||||
var result: MoreComplexExample # expected-note {{'result' declared here}}
|
||||
result.mem = MemExample()
|
||||
result.reg.reg2 = RegExample()
|
||||
self = result # expected-error {{use of uninitialized value 'result.reg.reg1'}}
|
||||
|
||||
def __deinit__(deinit self):
|
||||
pass
|
||||
|
||||
|
||||
def use(x: MoreComplexExample):
|
||||
pass
|
||||
|
||||
|
||||
def testClosure(a: Bool):
|
||||
if a:
|
||||
return
|
||||
|
||||
@always_inline
|
||||
def thing() capturing -> MemExample:
|
||||
var x: MemExample # expected-note {{'x' declared here}}
|
||||
return x # expected-error {{use of uninitialized value 'x'}}
|
||||
|
||||
_ = thing()
|
||||
|
||||
|
||||
# expected-error @+1 {{field 'x.mem' destroyed out of the middle of a value, preventing the overall value from being destroyed}}
|
||||
def disableDtor(var x: MoreComplexExample):
|
||||
x.mem^.consume()
|
||||
|
||||
|
||||
def fieldConsumeError(
|
||||
var w: MoreComplexExample, # expected-note {{'w' declared here}}
|
||||
# expected-error @+1 {{field 'x.mem' destroyed out of the middle of a value, preventing the overall value from being destroyed}}
|
||||
var x: MoreComplexExample,
|
||||
var y: MoreComplexExample,
|
||||
var z: MoreComplexExample, # expected-note {{'z' declared here}}
|
||||
):
|
||||
x.mem^.consume()
|
||||
|
||||
# This is ok because we replace the mem field.
|
||||
y.mem^.consume()
|
||||
|
||||
y.mem = MemExample()
|
||||
|
||||
z.mem^.consume()
|
||||
z.mem^.consume() # expected-error {{use of uninitialized value 'z.mem'}}
|
||||
z.mem = MemExample()
|
||||
|
||||
w.mem^.consume()
|
||||
use(w) # expected-error {{use of uninitialized value 'w.mem'}}
|
||||
|
||||
# expected-warning @+2 {{assignment to 'twoRegsRP' was never used; assign to '_' instead?}}
|
||||
# expected-error @+1 {{field 'twoRegsRP.reg1' destroyed out of the middle of a value, preventing the overall value from being destroyed}}
|
||||
var twoRegsRP = TwoRegsRP()
|
||||
twoRegsRP.reg1^.consume()
|
||||
|
||||
var single1 = MemExample() # expected-note {{'single1' declared here}}
|
||||
single1^.consume()
|
||||
_ = single1 # expected-error {{use of uninitialized value 'single1'}}
|
||||
|
||||
|
||||
# https://github.com/modularml/modular/issues/15404
|
||||
struct SimpleStructNoDtor(Movable where False):
|
||||
def __init__(out self):
|
||||
pass
|
||||
|
||||
|
||||
def consume(var x: SimpleStructNoDtor):
|
||||
pass
|
||||
|
||||
|
||||
def issue15404():
|
||||
var c = SimpleStructNoDtor() # expected-note {{'c' declared here}}
|
||||
consume(c^)
|
||||
consume(c^) # expected-error {{use of uninitialized value 'c'}}
|
||||
|
||||
|
||||
@fieldwise_init
|
||||
struct SP[n: Int](Movable where False):
|
||||
pass
|
||||
|
||||
|
||||
def test_no_unused_warning() -> Int:
|
||||
# expected-warning @+1 {{assignment to 's' was never used; assign to '_' instead?}}
|
||||
var s = SP[2]()
|
||||
# This is syntactically a use, but n is a parameter, so the warning does show up.
|
||||
return s.n
|
||||
|
||||
|
||||
struct TestUnused[T: RPTTrait](TrivialRegisterPassable):
|
||||
var thing: Self.T
|
||||
|
||||
def __init__(out self, xyz: Self):
|
||||
var other = xyz # should not warn about dead store.
|
||||
self.thing = other.thing
|
||||
_ = self.thing
|
||||
|
||||
|
||||
trait RPTTrait(TrivialRegisterPassable):
|
||||
pass
|
||||
|
||||
|
||||
##===----------------------------------------------------------------------===##
|
||||
# incorrect warnings
|
||||
##===----------------------------------------------------------------------===##
|
||||
|
||||
|
||||
# Consumption of struct works only on definition of __deinit__
|
||||
# https://github.com/modular/mojo/issues/734
|
||||
struct StructWithNoDel(Movable where False):
|
||||
var x: Int
|
||||
|
||||
@implicit
|
||||
def __init__(out self, a: Int):
|
||||
self.x = a
|
||||
|
||||
|
||||
def take(var x: StructWithNoDel):
|
||||
pass
|
||||
|
||||
|
||||
def testStructWithNoDel():
|
||||
var l = StructWithNoDel(100)
|
||||
# expected-error @below {{value 'l' cannot be consumed, because 'l.x' is used later}}
|
||||
take(l^)
|
||||
l.x = 10
|
||||
|
||||
|
||||
# expected-note @+1 {{'x' declared here}}
|
||||
def inout_restored_at_throw(mut x: MemExample) raises:
|
||||
# x is uninit after this point, needs to be restored if an
|
||||
# error is thrown.
|
||||
x^.consume()
|
||||
raise Error() # expected-error {{use of uninitialized value 'x'}}
|
||||
|
||||
|
||||
# Invalid error field 'w.x.y' destroyed out of the middle of a value, preventing the overall value from being destroyed
|
||||
# https://github.com/modular/mojo/issues/1535
|
||||
@fieldwise_init
|
||||
struct NestedInt(ImplicitlyCopyable):
|
||||
var y: Int
|
||||
|
||||
|
||||
@fieldwise_init
|
||||
struct WrapperNestedInt(Movable where False):
|
||||
var x: NestedInt
|
||||
|
||||
|
||||
@fieldwise_init
|
||||
struct TrivialRange(Iterator, TrivialRegisterPassable):
|
||||
comptime Element = Int
|
||||
|
||||
def __iter__(self) -> Self:
|
||||
return self
|
||||
|
||||
def __next__(mut self) raises StopIteration -> Int:
|
||||
return 1
|
||||
|
||||
def __len__(self) -> Int:
|
||||
return 1
|
||||
|
||||
|
||||
def testWrapperNestedInt():
|
||||
var w = WrapperNestedInt(NestedInt(0))
|
||||
for _ in TrivialRange():
|
||||
w.x.y = 0
|
||||
|
||||
|
||||
# ===----------------------------------------------------------------------=== #
|
||||
# More complex references
|
||||
# ===----------------------------------------------------------------------=== #
|
||||
|
||||
|
||||
def testConditionalImmut(cond: __mlir_type.`!kgen.scalar<bool>`):
|
||||
var a = MemExample()
|
||||
var b: MemExample # expected-note {{'b' declared here}}
|
||||
|
||||
var aptr = Pointer(to=a)
|
||||
# expected-error @+1 {{use of uninitialized value 'b'}}
|
||||
var bptr = Pointer(to=b)
|
||||
var cptr = aptr if cond else bptr
|
||||
|
||||
cptr[].noop()
|
||||
|
||||
|
||||
def testConditionalMut(cond: __mlir_type.`!kgen.scalar<bool>`):
|
||||
var a = MemExample()
|
||||
var b: MemExample # expected-note {{'b' declared here}}
|
||||
|
||||
# expected-error @+1 {{use of uninitialized value 'b'}}
|
||||
var cptr = Pointer(to=a) if cond else Pointer(to=b)
|
||||
cptr[] = MemExample()
|
||||
|
||||
|
||||
# CheckLifetimes cannot call MemExample.__deinit__ because 'self' is in the default
|
||||
# address space.
|
||||
def bad_addr_space[
|
||||
addr_space: AddressSpace
|
||||
](ptr: UnsafePointer[MemExample, address_space=addr_space, ...]):
|
||||
# expected-error @+1 {{cannot destroy value in non-default address space}}
|
||||
_ = __get_address_as_owned_value(ptr._get_kgen_pointer())
|
||||
|
||||
|
||||
# Returning a reference to the caller's stack.
|
||||
# https://github.com/modularml/modular/issues/38421
|
||||
# This is valid to declare...
|
||||
def return_owned_arg_ref(var x: String) -> Pointer[String, origin_of(x)]:
|
||||
return Pointer(to=x)
|
||||
|
||||
|
||||
def test38421():
|
||||
# this is getting a reference to the expression temporary for the string.
|
||||
# expected-note @+1 {{'(expression temporary)' declared here}}
|
||||
var reference = return_owned_arg_ref("abc")
|
||||
|
||||
# This is an error since the rvalue temp slot is uninitialized here.
|
||||
# expected-error @+1 {{use of uninitialized value '(expression temporary)'}}
|
||||
_ = reference[].__len__()
|
||||
|
||||
|
||||
@fieldwise_init
|
||||
struct MovableStuff(Movable):
|
||||
pass
|
||||
|
||||
|
||||
def test_cannot_consume_indirect_references():
|
||||
# expected-warning @+1 {{assignment to 'a' was never used}}
|
||||
var a = MovableStuff()
|
||||
# expected-warning @+1 {{assignment to 'b' was never used}}
|
||||
var b = MovableStuff()
|
||||
|
||||
@__parameter
|
||||
def callback():
|
||||
# expected-error @+1 {{cannot consume indirect references to values}}
|
||||
b = a^
|
||||
|
||||
|
||||
# ===----------------------------------------------------------------------=== #
|
||||
# Computed LValues
|
||||
# ===----------------------------------------------------------------------=== #
|
||||
|
||||
|
||||
def get_inout_ref(mut x: String) -> ref[x] String:
|
||||
return x
|
||||
|
||||
|
||||
struct StrArray(Movable where False):
|
||||
def __getitem__(self, x: Int) -> String:
|
||||
return String()
|
||||
|
||||
def __setitem__(mut self, x: Int, var value: String):
|
||||
pass
|
||||
|
||||
|
||||
def test_inout_ref(mut v: StrArray, i: Int):
|
||||
# expected-note @below {{'(expression temporary)' declared here}}
|
||||
# expected-error @below {{use of uninitialized value '(expression temporary)'}}
|
||||
var r = Pointer(to=get_inout_ref(v[i]))
|
||||
|
||||
_ = r[]
|
||||
|
||||
|
||||
def test_uninit_store_trivial():
|
||||
var example = TrivialAggregate()
|
||||
example.a = 1
|
||||
# expected-warning @+1 {{assignment to 'example.b' was never used}}
|
||||
example.b = 2
|
||||
|
||||
|
||||
def test_owned_warning(var arg: TrivialAggregate):
|
||||
# expected-warning @+1 {{assignment to 'arg' was never used}}
|
||||
arg = TrivialAggregate()
|
||||
|
||||
|
||||
struct TrivialAggregate(TrivialRegisterPassable):
|
||||
var a: Int
|
||||
var b: Int
|
||||
|
||||
def __init__(out self):
|
||||
self.a = 0
|
||||
self.b = 0
|
||||
|
||||
|
||||
def param_for_merge_diagnostic():
|
||||
# NOTE: shouldn't produce a "unused store" warning.
|
||||
var array_ptr = Int()
|
||||
|
||||
comptime for _ in TrivialRange():
|
||||
_ = array_ptr._mlir_value
|
||||
|
||||
|
||||
def raises_ret_int() raises -> Int:
|
||||
return 4
|
||||
|
||||
|
||||
def test_trivial_consume():
|
||||
var outshape: Int # expected-note {{'outshape' declared here}}
|
||||
try:
|
||||
outshape = raises_ret_int()
|
||||
except:
|
||||
pass
|
||||
|
||||
# expected-error @+1 {{use of uninitialized value 'outshape'}}
|
||||
_ = outshape
|
||||
|
||||
|
||||
def test_unused_var(mut mut_arg: Int):
|
||||
# expected-warning @+1 {{assignment to 'x' was never used; assign to '_' instead?}}
|
||||
var x: Int = 0
|
||||
|
||||
# expected-warning @+1 {{variable 'y' was never used, remove it?}}
|
||||
var y: Int
|
||||
|
||||
# expected-warning @+1 {{ref 'z' was never used, remove it?}}
|
||||
ref z = mut_arg
|
||||
|
||||
|
||||
@explicit_destroy("Use `consume() method` to finalize")
|
||||
@fieldwise_init
|
||||
struct LinearType(Deinitable where False, Movable where False):
|
||||
def consume(deinit self):
|
||||
pass
|
||||
|
||||
def use(self):
|
||||
pass
|
||||
|
||||
|
||||
def do_something() raises:
|
||||
pass
|
||||
|
||||
|
||||
def test_linear_type() raises:
|
||||
var tok1 = LinearType()
|
||||
|
||||
# expected-error @+1 {{'tok1' abandoned without being explicitly destroyed: Use `consume() method` to finalize}}
|
||||
tok1.use()
|
||||
|
||||
# MOCO-2275: Poor error when raises interacts with @explicit_destroy type
|
||||
var tok2 = LinearType()
|
||||
# expected-error @below {{'tok2' abandoned without being explicitly destroyed: Use `consume() method` to finalize}}
|
||||
# expected-note @below {{value was not consumed when an error is thrown}}
|
||||
do_something()
|
||||
|
||||
tok2^.consume()
|
||||
|
||||
|
||||
def test_linear_no_return_complex_lifetime(
|
||||
a: LinearType, mut b: LinearType, mut c: LinearType
|
||||
):
|
||||
_ = a
|
||||
b^.consume()
|
||||
abort() # Doesn't require 'a' or 'c' to be destroyed.
|
||||
|
||||
|
||||
# Hard case for conditional lifetime analysis on abort. This should compile.
|
||||
struct ReducedVariant(Deinitable where False, Movable where False):
|
||||
var _storage: ReducedStorage
|
||||
|
||||
def take[T: Movable](deinit self, cond: Bool) -> T:
|
||||
if cond:
|
||||
abort()
|
||||
return self._storage^.take[T]()
|
||||
|
||||
|
||||
struct ReducedStorage(Deinitable where False, Movable where False):
|
||||
def take[U: Movable](deinit self) -> U:
|
||||
abort()
|
||||
|
||||
|
||||
@explicit_destroy("This needs explicit destruction when T isn't linear")
|
||||
struct ConditionallyLinearType[T: AnyType](
|
||||
Deinitable where conforms_to(T, Deinitable), Movable where False
|
||||
):
|
||||
# var data: Self.T
|
||||
|
||||
def __init__(out self):
|
||||
pass
|
||||
|
||||
def use(self):
|
||||
pass
|
||||
|
||||
def __deinit__(deinit self) where conforms_to(Self.T, Deinitable):
|
||||
pass # self.data^.__deinit__()
|
||||
|
||||
|
||||
def testConditionallyLinearType():
|
||||
var c = ConditionallyLinearType[String]()
|
||||
c.use()
|
||||
|
||||
var d = ConditionallyLinearType[LinearType]()
|
||||
# expected-error @+1 {{'d' abandoned without being explicitly destroyed: This needs explicit destruction when T isn't linear}}
|
||||
d.use()
|
||||
|
||||
|
||||
# ===----------------------------------------------------------------------=== #
|
||||
# Trait-bound fields
|
||||
# ===----------------------------------------------------------------------=== #
|
||||
|
||||
|
||||
struct Pair[T: Movable & Deinitable](Movable):
|
||||
var first: Self.T
|
||||
var second: Self.T
|
||||
|
||||
def __init__(out self, var first: Self.T, var second: Self.T):
|
||||
self.first = first^
|
||||
self.second = second^
|
||||
|
||||
|
||||
def sink[T: AnyType](x: T):
|
||||
pass
|
||||
|
||||
|
||||
def test_trait_bound_field():
|
||||
# @expected-error @below {{field '(expression temporary).first' destroyed out of the middle of a value, preventing the overall value from being destroyed}}
|
||||
var r = Pair[List[Int]](List[Int](), List[Int]()).first^
|
||||
# To prevent optimization/warning on unused object
|
||||
sink(r)
|
||||
|
||||
|
||||
# ===----------------------------------------------------------------------=== #
|
||||
# Origin subtree views
|
||||
# ===----------------------------------------------------------------------=== #
|
||||
#
|
||||
# Subtree origins (x~) abstract over "some reference rooted within this owner"
|
||||
# without pinning the exact interior path.
|
||||
|
||||
struct ListPair:
|
||||
var left: List[Int]
|
||||
var right: List[Int]
|
||||
|
||||
def __init__(out self):
|
||||
self.left = List[Int]()
|
||||
self.right = List[Int]()
|
||||
|
||||
# Returning a ref with a subtree origin should be allowed when the returned
|
||||
# reference is rooted somewhere under the owner.
|
||||
def get_left_erased(ref self) -> ref[origin_of(self).subtree] List[Int]:
|
||||
return self.left
|
||||
|
||||
|
||||
# This function coerces a ref to a subtree based on the specified base.
|
||||
@__unsafe_nested_origins_read_only
|
||||
def get_subtree_ref[T: AnyType, //, subtree_root: Origin](ref [subtree_root.subtree] x: T)
|
||||
-> ref[subtree_root.subtree] T:
|
||||
return x
|
||||
|
||||
def test_subtree_return_borrow():
|
||||
var pair = ListPair()
|
||||
ref r = pair.get_left_erased()
|
||||
use(get_subtree_ref[origin_of(pair)](r))
|
||||
|
||||
# A precise interior ref should coerce to a wider subtree view of the same
|
||||
# owner (list["element"] <: ~list).
|
||||
var list = List[Int]()
|
||||
ref elt = list[0]
|
||||
use(get_subtree_ref[origin_of(list)](elt))
|
||||
|
||||
# Mutating the owner should invalidate live refs passed through subtree views.
|
||||
def test_subtree_invalidation_on_mutation():
|
||||
var list = List[Int]()
|
||||
ref elt = list[0]
|
||||
ref elt_erased = get_subtree_ref[origin_of(list)](elt)
|
||||
use(elt_erased)
|
||||
list.append(42) # expected-note {{origin was invalidated here}}
|
||||
# expected-error @+1 {{use of invalidated interior reference 'origin_of(list).subtree'}}
|
||||
use(elt_erased)
|
||||
|
||||
# Read-only use of the owner should not invalidate interior refs.
|
||||
def test_subtree_survives_readonly_access():
|
||||
var list = List[Int]()
|
||||
ref erased_elt = get_subtree_ref[origin_of(list)](list[0])
|
||||
_ = list.__len__()
|
||||
use(erased_elt)
|
||||
|
||||
# Field-sensitive: mutating one field should not invalidate refs rooted under
|
||||
# a sibling field, even when passed to a ~pair.left API.
|
||||
def test_subtree_field_scoped_invalidation():
|
||||
var pair = ListPair()
|
||||
ref left_elt = get_subtree_ref[origin_of(pair.left)](pair.left[0])
|
||||
ref right_elt = get_subtree_ref[origin_of(pair.right)](pair.right[0])
|
||||
pair.left.append(1) # expected-note {{origin was invalidated here}}
|
||||
# expected-error @+1 {{use of invalidated interior reference 'origin_of(pair.left).subtree'}}
|
||||
use(left_elt)
|
||||
# This is ok.
|
||||
use(right_elt)
|
||||
|
||||
def test_simple_subtree_mut_invalidation(var collection: List[Int]):
|
||||
ref x = get_subtree_ref[origin_of(collection).subtree](collection[4])
|
||||
x += 1 # expected-note {{origin was invalidated here}}
|
||||
x += 1 # expected-error {{use of invalidated interior reference 'origin_of(collection).subtree'}}
|
||||
|
||||
def get_raising(var list: List[Int]) raises -> ref [origin_of(list).subtree] Int:
|
||||
return list[0]
|
||||
|
||||
struct ListAndInt:
|
||||
var list: List[Int]
|
||||
var anotherInt: Int
|
||||
|
||||
# This can return a reference into list and also a reference to anotherInt.
|
||||
def get_someint(ref self, cond: Bool) -> ref[origin_of(self).subtree] Int:
|
||||
if cond:
|
||||
return self.list[4]
|
||||
else:
|
||||
return self.anotherInt
|
||||
|
||||
def test_complex_subtree_mut_invalidation(var list_and_int: ListAndInt):
|
||||
ref r1 = list_and_int.get_someint(True)
|
||||
r1 += 1 # Can mutate this.
|
||||
|
||||
ref r2 = list_and_int.get_someint(True)
|
||||
list_and_int.list.append(1) # expected-note {{origin was invalidated here}}
|
||||
use(r2) # expected-error {{use of invalidated interior reference 'origin_of(list_and_int).subtree'}}
|
||||
|
||||
def test_complex_subtree_mut_invalidation_2(var list_and_int: ListAndInt):
|
||||
ref r1 = list_and_int.get_someint(False)
|
||||
list_and_int.anotherInt += 1 # expected-note {{origin was invalidated here}}
|
||||
use(r1) # expected-error {{use of invalidated interior reference 'origin_of(list_and_int).subtree'}}
|
||||
|
||||
struct MiniDict:
|
||||
@__unsafe_nested_origins_read_only
|
||||
def __getitem__(ref self, idx: String) raises String -> ref[origin_of(self).subtree] String:
|
||||
raise ""
|
||||
|
||||
def use_two_strings(a: String, b: String): pass
|
||||
|
||||
def test_control_flow_invalidation(var d : MiniDict) raises:
|
||||
var str = ""
|
||||
ref entry = d[str]
|
||||
use_two_strings(d[entry], entry)
|
||||
@@ -0,0 +1,461 @@
|
||||
# ===----------------------------------------------------------------------=== #
|
||||
# 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.
|
||||
# ===----------------------------------------------------------------------=== #
|
||||
|
||||
# RUN: %parse-mojo-isolated %s --mlir-print-debuginfo -o %t.mlir
|
||||
# RUN: kgen-opt %t.mlir -lower-semantic-cf -check-lifetimes -verify-parameters -verify-diagnostics | FileCheck %s
|
||||
# RUN: %parse-mojo-isolated %s --debug-level full -o /dev/null
|
||||
|
||||
# Error Handling related CheckLifetimes tests.
|
||||
|
||||
|
||||
def use(x: Int):
|
||||
pass
|
||||
|
||||
|
||||
def use(x: String):
|
||||
pass
|
||||
|
||||
|
||||
def use_and_raise(x: Int) raises:
|
||||
pass
|
||||
|
||||
|
||||
# CHECK-LABEL: lit.struct.decl @RegExample
|
||||
struct RegExample(ImplicitlyCopyable, RegisterPassable):
|
||||
def __init__(out self):
|
||||
return
|
||||
|
||||
# CHECK: lit.fn @"__init__{{.*}}"{{.*}}(*, %copy:
|
||||
def __init__(out self, *, copy: Self):
|
||||
return
|
||||
|
||||
# Test a raising constructor.
|
||||
# CHECK-LABEL: lit.fn @"__init__{{.*}}(%a: {{.*}}, %b: {{.*}}, ?, %__error__: !lit.ref<!Error, {{.*}}> byref_error, %self: !lit.ref<!RegExample, {{.*}}> byref_result) throws -> !kgen.scalar<bool>
|
||||
def __init__(out self, a: MemExample, b: MemExample) raises:
|
||||
# CHECK-NOT: __deinit__
|
||||
# CHECK: [[FALSE:%.*]] = kgen.param.constant: scalar<bool> = <false>
|
||||
# CHECK-NEXT: kgen.return [[FALSE]]
|
||||
return
|
||||
|
||||
def noop(self):
|
||||
pass
|
||||
|
||||
def __deinit__(deinit self):
|
||||
pass
|
||||
|
||||
def mutate(mut self):
|
||||
pass
|
||||
|
||||
|
||||
struct MemExample(ImplicitlyCopyable):
|
||||
var x: Int
|
||||
|
||||
def __init__(out self):
|
||||
self.x = 42
|
||||
pass
|
||||
|
||||
def noop(self):
|
||||
pass
|
||||
|
||||
def __init__(out self, *, deinit move: Self):
|
||||
self.x = move.x
|
||||
|
||||
def __init__(out self, *, copy: Self):
|
||||
self.x = copy.x
|
||||
|
||||
def __bool__(self) -> Bool:
|
||||
return True
|
||||
|
||||
def __deinit__(deinit self):
|
||||
pass
|
||||
|
||||
|
||||
# Use of uninitialized value after call to def function
|
||||
|
||||
|
||||
# CHECK-LABEL: lit.fn @"error_handling_int_let
|
||||
# https://github.com/modularml/modular/issues/25419
|
||||
def error_handling_int_let() raises:
|
||||
# CHECK: lit.var.decl "x"
|
||||
var x: Int = 1
|
||||
_ = use_and_raise(x)
|
||||
use(x)
|
||||
|
||||
|
||||
def somethingThatRaises() raises:
|
||||
pass
|
||||
|
||||
|
||||
# CHECK-LABEL: lit.fn @"thing_that_raises
|
||||
def thing_that_raises(c: __mlir_type.`!kgen.scalar<bool>`) raises -> MemExample:
|
||||
# CHECK-NEXT: [[RESULT:%.*]] = lit.var.decl "__call_result_tmp__" synth : !lit.ref<none,
|
||||
# CHECK-NEXT: lifetime.start [[RESULT]]
|
||||
# CHECK-NEXT: [[IS_ERR:%.*]] = lit.call {{.*}}somethingThatRaises{{.*}}(%__error__, [[RESULT]])
|
||||
# CHECK-NEXT: hlcf.if [[IS_ERR]]
|
||||
# CHECK-NEXT: mark_consumed [[RESULT]]
|
||||
# CHECK-NEXT: lifetime.end [[RESULT]]
|
||||
# CHECK-NEXT: [[TRUE:%.*]] = kgen.param.constant: scalar<bool> = <true>
|
||||
# CHECK-NEXT: lit.error_return [[TRUE]]
|
||||
# CHECK-NEXT: } else {
|
||||
# CHECK-NEXT: lifetime.end [[RESULT]]
|
||||
# CHECK-NEXT: mark_consumed %__error__
|
||||
# CHECK-NEXT: yield
|
||||
# CHECK-NEXT: }
|
||||
somethingThatRaises()
|
||||
|
||||
# CHECK-NEXT: hlcf.elif %c {
|
||||
# CHECK-NEXT: = lit.call {{.*}}__init__
|
||||
# CHECK-NOT: __deinit__
|
||||
# CHECK: kgen.return
|
||||
if c:
|
||||
return MemExample()
|
||||
# CHECK-NEXT: } else {
|
||||
raise Error("TypeError: cannot invert values of this type")
|
||||
|
||||
|
||||
struct RaisingInit(Movable where False):
|
||||
var stream: Int
|
||||
|
||||
def __init__(out self, flags: Int = 0) raises:
|
||||
var stream = 4
|
||||
# This can raise, but 'self' doesn't need to be initialized.
|
||||
_ = somethingThatRaises()
|
||||
self.stream = stream
|
||||
|
||||
|
||||
# CHECK-LABEL: lit.fn @"finally_may_raise
|
||||
def finally_may_raise() raises:
|
||||
# CHECK: lit.try
|
||||
try:
|
||||
# CHECK-NEXT: lifetime.start %__try_error__
|
||||
# CHECK-NEXT: [[TMP:%.*]] = lit.call {{.*}}__init__{{.*}}(%__try_error__)
|
||||
# CHECK-NEXT: lit.try.raise
|
||||
raise Error()
|
||||
# CHECK-NEXT: } except {
|
||||
# CHECK-NEXT: lit.call {{.*}}Error::@"__init__{{.*}}"{{.*}}(%__try_error__, %__error__){{.*}}*, "move"
|
||||
# CHECK-NEXT: lit.var.lifetime.end %__try_error__
|
||||
# CHECK-NEXT: [[TRUE:%.*]] = kgen.param.constant: scalar<bool> = <true>
|
||||
# CHECK-NEXT: %__finally_error__ = lit.var.decl
|
||||
# CHECK-NEXT: lit.try
|
||||
# CHECK-NEXT: [[RESULT:%.*]] = lit.var.decl
|
||||
# CHECK-NEXT: lifetime.start %__finally_error__
|
||||
# CHECK-NEXT: lifetime.start [[RESULT]]
|
||||
# CHECK-NEXT: [[IS_ERR:%.*]] = lit.call {{.*}}somethingThatRaises{{.*}}(%__finally_error__, [[RESULT]])
|
||||
# CHECK-NEXT: if [[IS_ERR]]
|
||||
# CHECK-NEXT: call {{.*}}__deinit__{{.*}}(%__error__)
|
||||
# CHECK-NEXT: mark_consumed [[RESULT]]
|
||||
# CHECK: } except {
|
||||
# CHECK-NEXT: lit.call {{.*}}Error::@"__init__{{.*}}"{{.*}}(%__finally_error__, %__error__){{.*}}*, "move"
|
||||
# CHECK-NEXT: lit.var.lifetime.end %__finally_error__
|
||||
# CHECK: else
|
||||
# CHECK-NEXT: lit.try.yield
|
||||
# CHECK-NEXT: }
|
||||
# CHECK-NEXT: lit.error_return [[TRUE]]
|
||||
finally:
|
||||
somethingThatRaises()
|
||||
|
||||
|
||||
@fieldwise_init
|
||||
struct ThrowingExit(Movable where False):
|
||||
def __enter__(self):
|
||||
pass
|
||||
|
||||
def __deinit__(deinit self):
|
||||
pass
|
||||
|
||||
def __exit__(self) raises:
|
||||
pass
|
||||
|
||||
def __exit__(self, e: Error) raises -> Bool:
|
||||
return False
|
||||
|
||||
|
||||
# CHECK-LABEL: lit.fn @"context_mgr_exit_raises
|
||||
def context_mgr_exit_raises() raises:
|
||||
# CHECK: lit.call {{.*}}Error::@"__init__{{.*}}"{{.*}}(%__with_error__, %__error__){{.*}}*, "move"
|
||||
# CHECK-NEXT: lit.var.lifetime.end %__with_error__
|
||||
# CHECK-NEXT: [[TRUE:%.*]] = kgen.param.constant: scalar<bool> = <true>
|
||||
# CHECK-NEXT: %__finally_error__ = lit.var.decl
|
||||
# CHECK-NEXT: lit.try
|
||||
# CHECK-NEXT: [[DID_ERR:%.*]] = lit.ref.load %__with_exc__
|
||||
# CHECK-NEXT: lifetime.end %__with_exc__
|
||||
# CHECK-NEXT: hlcf.elif [[DID_ERR]]
|
||||
# CHECK-NEXT: [[IMM:%.*]] = lit.ref.immut %$CONTEXTMGR
|
||||
# CHECK-NEXT: [[BOOL:%.*]] = lit.var.decl
|
||||
# CHECK-NEXT: lit.var.lifetime.start %__finally_error__
|
||||
# CHECK-NEXT: lit.var.lifetime.start [[BOOL]]
|
||||
# CHECK-NEXT: [[IS_ERR:%.*]] = lit.call {{.*}}__exit__{{.*}}([[IMM]], %__finally_error__, [[BOOL]])
|
||||
# CHECK-NEXT: call {{.*}}__deinit__{{.*}}(%$CONTEXTMGR)
|
||||
# CHECK-NEXT: lit.var.lifetime.end %$CONTEXTMGR
|
||||
# CHECK-NEXT: if [[IS_ERR]]
|
||||
# CHECK-NEXT: call {{.*}}__deinit__{{.*}}(%__error__)
|
||||
# CHECK-NEXT: mark_consumed [[BOOL]]
|
||||
# CHECK-NEXT: lit.var.lifetime.end [[BOOL]]
|
||||
# CHECK: else
|
||||
# CHECK-NEXT: lit.var.lifetime.end [[BOOL]]
|
||||
# CHECK-NEXT: mark_consumed %__finally_error__
|
||||
# CHECK-NEXT: lit.var.lifetime.end %__finally_error__
|
||||
# CHECK-NEXT: yield
|
||||
# CHECK: else
|
||||
# CHECK-NEXT: call {{.*}}__deinit__{{.*}}(%$CONTEXTMGR)
|
||||
# CHECK: } except {
|
||||
# CHECK-NEXT: lit.call {{.*}}Error::@"__init__{{.*}}"{{.*}}(%__finally_error__, %__error__){{.*}}*, "move"
|
||||
# CHECK-NEXT: lit.var.lifetime.end %__finally_error__
|
||||
# CHECK: else
|
||||
# CHECK-NEXT: lit.try.yield
|
||||
# CHECK-NEXT: }
|
||||
# CHECK-NEXT: lit.error_return [[TRUE]]
|
||||
with ThrowingExit():
|
||||
raise Error()
|
||||
|
||||
|
||||
def may_throw() raises -> RegExample:
|
||||
return RegExample()
|
||||
|
||||
|
||||
# CHECK-LABEL: lit.fn @"propagate_reg_error
|
||||
def propagate_reg_error() raises:
|
||||
# CHECK-NEXT: [[RESULT:%.*]] = lit.var.decl "__call_result_tmp__" synth : !lit.ref<!RegExample,
|
||||
# CHECK-NEXT: lifetime.start [[RESULT]]
|
||||
# CHECK-NEXT: %0 = lit.call {{.*}}may_throw{{.*}}(%__error__, [[RESULT]])
|
||||
# CHECK-NEXT: if %0
|
||||
# CHECK: lifetime.end [[RESULT]]
|
||||
# CHECK: lit.error_return
|
||||
# CHECK-NEXT: } else {
|
||||
# CHECK-NEXT: mark_consumed %__error__
|
||||
# CHECK-NEXT: yield
|
||||
# CHECK-NEXT: }
|
||||
# CHECK-NEXT: lit.ownership.use [[RESULT]]
|
||||
# CHECK-NEXT: lit.call {{.*}}@RegExample::@"__deinit__{{.*}}([[RESULT]])
|
||||
# CHECK-NEXT: lifetime.end [[RESULT]]
|
||||
_ = may_throw()
|
||||
# CHECK-NEXT: %none = kgen.param.constant: none
|
||||
# CHECK-NEXT: lit.ref.store %none, %__result__
|
||||
# CHECK-NEXT: [[FALSE:%.*]] = kgen.param.constant: scalar<bool> = <false>
|
||||
# CHECK-NEXT: kgen.return [[FALSE]]
|
||||
|
||||
|
||||
# CHECK-LABEL: lit.struct.decl @BigRegExample
|
||||
struct BigRegExample(RegisterPassable):
|
||||
var a: RegExample
|
||||
var b: RegExample
|
||||
|
||||
# Test a raising constructor.
|
||||
# CHECK-LABEL: lit.fn @"__init__{{.*}}MemExample{{.*}}MemExample
|
||||
def __init__(out self, a: MemExample, b: MemExample) raises:
|
||||
# CHECK-NEXT: [[A_REF:%.*]] = lit.ref.struct.ger %self[a]
|
||||
# CHECK-NEXT: [[A:%.*]] = lit.call {{.*}}__init__{{.*}}()
|
||||
# CHECK-NEXT: lit.ref.store [[A]], [[A_REF]]
|
||||
self.a = RegExample()
|
||||
# CHECK-NEXT: [[B_REF:%.*]] = lit.ref.struct.ger %self[b]
|
||||
# CHECK-NEXT: [[B:%.*]] = lit.call {{.*}}__init__{{.*}}()
|
||||
# CHECK-NEXT: lit.ref.store [[B]], [[B_REF]]
|
||||
self.b = RegExample()
|
||||
# CHECK-NEXT: [[FALSE:%.*]] = kgen.param.constant: scalar<bool> = <false>
|
||||
# CHECK-NEXT: kgen.return [[FALSE]]
|
||||
|
||||
|
||||
struct MyStringReturningCtx(Movable):
|
||||
var s: String
|
||||
|
||||
def __init__(out self):
|
||||
self.s = "hey"
|
||||
|
||||
def __enter__(var self) -> Self:
|
||||
return self^
|
||||
|
||||
def read(self) raises -> String:
|
||||
return ""
|
||||
|
||||
|
||||
# CHECK: lit.fn @"testErrorReturn
|
||||
def testErrorReturn() raises:
|
||||
var input: String
|
||||
# CHECK: try
|
||||
with MyStringReturningCtx() as ctx:
|
||||
# CHECK-NOT: @MyStringReturningCtx::@"__deinit__
|
||||
var x = (
|
||||
ctx.read()
|
||||
) # expected-warning {{assignment to 'x' was never used}}
|
||||
input = "hello"
|
||||
# CHECK: except
|
||||
use(input)
|
||||
|
||||
|
||||
# COM: Test partial destruction of initialized fields upon an error return.
|
||||
struct Field(ImplicitlyCopyable):
|
||||
def __init__(out self, *, copy: Self):
|
||||
pass
|
||||
|
||||
def __deinit__(deinit self):
|
||||
pass
|
||||
|
||||
|
||||
# CHECK-LABEL: lit.struct.decl @DestructSome
|
||||
struct DestructSome(Movable where False):
|
||||
var a: Field
|
||||
var b: Field
|
||||
|
||||
# CHECK-LABEL: lit.fn @"__init__
|
||||
def __init__(out self, a: Field, b: Field) raises:
|
||||
# CHECK: lifetime.start %__call_result_tmp__
|
||||
# CHECK-NEXT: call {{.*}}somethingThatRaises
|
||||
# CHECK-NEXT: if
|
||||
# CHECK-NEXT: mark_consumed
|
||||
# CHECK-NEXT: lifetime.end %__call_result_tmp__
|
||||
# CHECK-NEXT: kgen.param.constant
|
||||
# CHECK-NEXT: lit.error_return
|
||||
somethingThatRaises()
|
||||
|
||||
# CHECK: [[FIELD:%.*]] = lit.ref.struct.ger %self[a]
|
||||
# CHECK-NEXT: __init__{{.*}}"{{.*}}(%a, [[FIELD]]){{.*}}*, "copy"
|
||||
self.a = a
|
||||
|
||||
# CHECK: lifetime.start %__call_result_tmp__
|
||||
# CHECK-NEXT: call {{.*}}somethingThatRaises
|
||||
# CHECK-NEXT: if
|
||||
# CHECK-NEXT: [[FIELD:%.*]] = lit.ref.struct.ger %self[a]
|
||||
# CHECK-NEXT: __deinit__{{.*}}([[FIELD]])
|
||||
# CHECK-NEXT: mark_consumed %__call_result_tmp__
|
||||
# CHECK-NEXT: lifetime.end %__call_result_tmp__
|
||||
# CHECK-NEXT: kgen.param.constant
|
||||
# CHECK-NEXT: lit.error_return
|
||||
somethingThatRaises()
|
||||
|
||||
# CHECK: [[FIELD:%.*]] = lit.ref.struct.ger %self[b]
|
||||
# CHECK-NEXT: __init__{{.*}}"{{.*}}(%b, [[FIELD]]){{.*}}*, "copy"
|
||||
self.b = b
|
||||
|
||||
# At this point 'self' is fully initialized, so any exit out should
|
||||
# destroy the whole thing.
|
||||
|
||||
# CHECK: lifetime.start %__call_result_tmp__
|
||||
# CHECK-NEXT: call {{.*}}somethingThatRaises
|
||||
# CHECK-NEXT: if
|
||||
# CHECK-NEXT: __deinit__{{.*}}(%self)
|
||||
# CHECK-NEXT: mark_consumed %__call_result_tmp__
|
||||
# CHECK-NEXT: lifetime.end %__call_result_tmp__
|
||||
# CHECK-NEXT: kgen.param.constant
|
||||
# CHECK-NEXT: lit.error_return
|
||||
somethingThatRaises()
|
||||
|
||||
|
||||
def borrow_and_return(value: MemExample) raises -> MemExample:
|
||||
return value
|
||||
|
||||
|
||||
def use(err: Error):
|
||||
pass
|
||||
|
||||
|
||||
# CHECK-LABEL: lit.fn @"raising_use
|
||||
def raising_use(var value: MemExample):
|
||||
try:
|
||||
# CHECK: [[BORROW:%.*]] = lit.ref.immut %value
|
||||
# CHECK-NEXT: [[VAL:%.*]] = lit.var.decl "__call_result_tmp__"
|
||||
# CHECK-NEXT: lifetime.start %__try_error__
|
||||
# CHECK-NEXT: lifetime.start [[VAL]]
|
||||
# CHECK-NEXT: [[IS_ERR:%.*]] = lit.call {{.*}}borrow_and_return{{.*}}([[BORROW]], %__try_error__, [[VAL]])
|
||||
# CHECK-NEXT: call {{.*}}@MemExample::@"__deinit__{{.*}}(%value)
|
||||
# CHECK-NEXT: if [[IS_ERR]]
|
||||
# CHECK-NEXT: call {{.*}}@Error::@"__deinit__{{.*}}(%__try_error__)
|
||||
# CHECK-NEXT: lit.var.lifetime.end %__try_error__
|
||||
# CHECK-NEXT: mark_consumed [[VAL]]
|
||||
# CHECK-NEXT: lit.var.lifetime.end [[VAL]]
|
||||
# CHECK-NEXT: lit.try.raise
|
||||
# CHECK-NEXT: } else {
|
||||
# CHECK-NEXT: mark_consumed %__try_error__
|
||||
# CHECK-NEXT: lit.var.lifetime.end %__try_error__
|
||||
# CHECK-NEXT: hlcf.yield
|
||||
# CHECK-NEXT: }
|
||||
# CHECK-NEXT: lit.ownership.use [[VAL]]
|
||||
# CHECK-NEXT: call {{.*}}@MemExample::@"__deinit__{{.*}}([[VAL]])
|
||||
# CHECK-NEXT: lifetime.end [[VAL]]
|
||||
_ = borrow_and_return(value)
|
||||
except:
|
||||
pass
|
||||
|
||||
|
||||
# CHECK-LABEL: lit.struct.decl @ThrowingSelfInit
|
||||
struct ThrowingSelfInit(Movable where False):
|
||||
var x: Int
|
||||
|
||||
def __deinit__(deinit self):
|
||||
pass
|
||||
|
||||
# CHECK-LABEL: lit.fn @"__init__
|
||||
def __init__(out self) raises:
|
||||
self.x = 0
|
||||
|
||||
# CHECK-LABEL: lit.fn @"__init__
|
||||
def __init__(out self, x: Int) raises:
|
||||
# CHECK-NEXT: [[IS_ERR:%.*]] = lit.call {{.*}}__init__{{.*}}(%__error__, %self)
|
||||
# CHECK-NEXT: if [[IS_ERR]]
|
||||
# CHECK-NEXT: mark_consumed %self
|
||||
# CHECK-NEXT: [[TRUE:%.*]] = kgen.param.constant
|
||||
# CHECK-NEXT: error_return [[TRUE]]
|
||||
# CHECK-NEXT: else
|
||||
# CHECK-NEXT: mark_consumed %__error__
|
||||
# CHECK-NEXT: yield
|
||||
self = ThrowingSelfInit()
|
||||
|
||||
# CHECK-LABEL: lit.fn @"__init__
|
||||
def __init__(out self, x: Int, y: Int) raises:
|
||||
# CHECK-NEXT: [[IS_ERR:%.*]] = lit.call {{.*}}__init__{{.*}}(%__error__, %self)
|
||||
# CHECK: else
|
||||
# CHECK-NEXT: call {{.*}}__deinit__{{.*}}(%self)
|
||||
# CHECK-NEXT: mark_consumed %__error__
|
||||
# CHECK-NEXT: yield
|
||||
self = ThrowingSelfInit()
|
||||
# CHECK: lit.call {{.*}}__init__{{.*}}(%__error__, %self)
|
||||
self = ThrowingSelfInit()
|
||||
|
||||
|
||||
struct InitFieldsDestroyedInThrowingConstructor(Movable where False):
|
||||
var x: MemExample
|
||||
|
||||
def __init__(out self):
|
||||
self.x = MemExample()
|
||||
|
||||
# CHECK-LABEL: lit.fn @"__init__(!kgen.scalar<bool>)"
|
||||
def __init__(out self, cond: __mlir_type.`!kgen.scalar<bool>`) raises:
|
||||
self = InitFieldsDestroyedInThrowingConstructor()
|
||||
# CHECK: hlcf.elif %cond {
|
||||
# CHECK-NEXT: lit.call {{.*}}__deinit__{{.*}}(%self)
|
||||
# CHECK-NEXT: lit.call {{.*}}::@Error::@"__init__
|
||||
# CHECK-NEXT: kgen.param.constant
|
||||
# CHECK-NEXT: lit.error_return
|
||||
# CHECK-NEXT: } else {
|
||||
# CHECK-NEXT: hlcf.yield
|
||||
# CHECK-NEXT: }
|
||||
if cond:
|
||||
raise Error()
|
||||
|
||||
|
||||
# CHECK-LABEL: lit.fn @"doesnt_actually_raise{{.*}}%__error__: !lit.ref<:non_struct_type #alias_Never
|
||||
def doesnt_actually_raise() raises Never:
|
||||
pass
|
||||
|
||||
|
||||
# CHECK-LABEL: lit.fn @"test_doesnt_actually_raise{{.*}}() -> !alias_Int1
|
||||
# CHECK-NEXT: %__never_error__ = lit.var.decl
|
||||
# CHECK-NEXT: %__call_result_tmp__ = lit.var.decl
|
||||
# CHECK-NEXT: lit.var.lifetime.start %__never_error__
|
||||
# CHECK-NEXT: lit.var.lifetime.start %__call_result_tmp__
|
||||
# CHECK-NEXT: lit.call {{.*}}doesnt_actually_raise{{.*}}(%__never_error__, %__call_result_tmp__)
|
||||
# CHECK-NEXT: lit.var.lifetime.end %__call_result_tmp__
|
||||
# CHECK-NEXT: lit.var.lifetime.end %__never_error__
|
||||
# CHECK-NEXT: kgen.param.constant: !alias_Int1 = <rebind(:!Int {:scalar<index> 42})>
|
||||
def test_doesnt_actually_raise() -> Int:
|
||||
doesnt_actually_raise()
|
||||
return 42
|
||||
@@ -0,0 +1,606 @@
|
||||
# ===----------------------------------------------------------------------=== #
|
||||
# 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 more advanced reference cases.
|
||||
|
||||
# RUN: %parse-mojo-isolated %s --mlir-print-debuginfo -o %t.mlir
|
||||
# RUN: kgen-opt %t.mlir -lower-semantic-cf -check-lifetimes -verify-parameters -verify-diagnostics | FileCheck %s
|
||||
|
||||
def use_any[*Ts: AnyType](*args: *Ts): pass
|
||||
|
||||
# ===----------------------------------------------------------------------=== #
|
||||
# Parsing of references
|
||||
# ===----------------------------------------------------------------------=== #
|
||||
|
||||
# CHECK-LABEL: lit.struct.decl @MemExample
|
||||
struct MemExample(ImplicitlyCopyable):
|
||||
def __init__(out self): pass
|
||||
def __init__(out self, *, deinit move: Self): pass
|
||||
def __init__(out self, *, copy: Self): pass
|
||||
def __deinit__(deinit self): pass
|
||||
def noop(self): pass
|
||||
def mutate(mut self): pass
|
||||
|
||||
# CHECK-LABEL: lit.fn @"borrow{{.*}}"<{{.*}}>(%a: !lit.ref<!MemExample, imm *"lt._mlir_origin`">
|
||||
def borrow[lt: ImmOrigin](a: Pointer[MemExample, lt]._mlir_lit_ref):
|
||||
pass
|
||||
|
||||
# CHECK-LABEL: lit.fn @"mutate{{.*}}"<{{.*}}>(%a: !lit.ref<!MemExample, mut *"lt._mlir_origin`">
|
||||
def mutate[lt: MutOrigin](a: Pointer[MemExample, lt]._mlir_lit_ref):
|
||||
pass
|
||||
|
||||
# CHECK-LABEL: lit.fn @"implicit_borrow
|
||||
def implicit_borrow(a: MemExample):
|
||||
pass
|
||||
|
||||
# CHECK-LABEL: lit.fn @"implicit_inout
|
||||
def implicit_inout(mut a: MemExample):
|
||||
pass
|
||||
|
||||
# CHECK-LABEL: lit.fn @"implicit_owned
|
||||
def implicit_owned(var a: MemExample):
|
||||
pass
|
||||
|
||||
# This preserves reference mutability
|
||||
# CHECK-LABEL: lit.fn @"parametricMut
|
||||
# CHECK-SAME: (%a: !lit.ref<!MemExample, mut=#lit.struct.extract<:!Bool *"o.mut`", "_mlir_value">, *"o._mlir_origin`1">) ->
|
||||
# CHECK-SAME: !lit.ref<!MemExample, mut=#lit.struct.extract<:!Bool *"o.mut`", "_mlir_value">, *"o._mlir_origin`1">
|
||||
def parametricMut[o: Origin](a: Pointer[MemExample, o]._mlir_lit_ref)
|
||||
-> Pointer[MemExample, o]._mlir_lit_ref:
|
||||
return a
|
||||
|
||||
# CHECK-LABEL: lit.fn @"testParametricMut
|
||||
def testParametricMut(i: MemExample, mut m: MemExample):
|
||||
# This infers an immutable reference.
|
||||
# CHECK: lit.call {{.*}}parametricMut{{.*}}!lit.ref<!MemExample, imm *"i`">
|
||||
_ = parametricMut(__get_mvalue_as_litref(i))
|
||||
|
||||
# This infers a mutable reference.
|
||||
# CHECK: lit.call {{.*}}parametricMut{{.*}}!lit.ref<!MemExample, mut *"m`1">
|
||||
_ = parametricMut(__get_mvalue_as_litref(m))
|
||||
|
||||
##===----------------------------------------------------------------------===##
|
||||
# Conditional origins
|
||||
##===----------------------------------------------------------------------===##
|
||||
|
||||
# CHECK-LABEL: lit.fn @"testUseConditional
|
||||
def testUseConditional(cond: __mlir_type.`!kgen.scalar<bool>`):
|
||||
# CHECK-NOT: __deinit__
|
||||
|
||||
# CHECK: lit.call {{.*}}__init__{{.*}}(%a)
|
||||
var a = MemExample()
|
||||
|
||||
# CHECK: lit.call {{.*}}__init__{{.*}}(%b)
|
||||
var b = MemExample()
|
||||
|
||||
# CHECK: %cptr = lit.var.decl "cptr"
|
||||
var cptr = Pointer(to=a) if cond else Pointer(to=b)
|
||||
|
||||
# This uses both A and B, so it needs to extend both of their origins.
|
||||
cptr[].noop()
|
||||
# CHECK: [[TMP:%.*]] = kgen.rebind %cptr
|
||||
# CHECK: [[CV:%.*]] = lit.ref.load [[TMP]]
|
||||
# CHECK-NEXT: lit.var.lifetime.end %cptr
|
||||
# CHECK-NEXT: [[MREF:%.*]] = lit.call {{.*}}__getitem__{{.*}}([[CV]])
|
||||
# CHECK-NEXT: lit.ref.immut [[MREF]]
|
||||
# CHECK-NEXT: lit.call {{.*}}noop
|
||||
# CHECK-NEXT: lit.call {{.*}}__deinit__{{.*}}(%b)
|
||||
# CHECK-NEXT: lifetime.end %b
|
||||
# CHECK-NEXT: lit.call {{.*}}__deinit__{{.*}}(%a)
|
||||
# CHECK-NEXT: lifetime.end %a
|
||||
|
||||
# CHECK-LABEL: lit.fn @"testDefConditional
|
||||
def testDefConditional(cond: __mlir_type.`!kgen.scalar<bool>`):
|
||||
# CHECK-NOT: lit.call {{[^)]*}}__deinit__
|
||||
|
||||
var a = MemExample()
|
||||
var b = MemExample()
|
||||
|
||||
# CHECK: %cptr = lit.var.decl "cptr"
|
||||
var cptr = Pointer(to=a) if cond else Pointer(to=b)
|
||||
|
||||
|
||||
# Mutating either of these is fine - it doesn't matter which one is mutated,
|
||||
# we know that both are live.
|
||||
cptr[].mutate()
|
||||
# CHECK: [[TMP:%.*]] = kgen.rebind %cptr
|
||||
# CHECK: [[CP:%.*]] = lit.ref.load [[TMP]]
|
||||
# CHECK-NEXT: [[MREF:%.*]] = lit.call {{.*}}__getitem__{{.*}}([[CP]])
|
||||
# CHECK-NEXT: lit.call {{.*}}mutate{{.*}}([[MREF]])
|
||||
|
||||
# Overwriting one means that we need to immediately destroy the same reference
|
||||
# because we cannot know which one is being set.
|
||||
cptr[] = MemExample()
|
||||
# CHECK: [[TMP:%.*]] = kgen.rebind %cptr
|
||||
# CHECK-NEXT: [[CP:%.*]] = lit.ref.load [[TMP]]
|
||||
# CHECK-NEXT: [[MREF:%.*]] = lit.call {{.*}}__getitem__{{.*}}([[CP]])
|
||||
# CHECK-NEXT: lit.call {{.*}}__deinit__{{.*}}([[MREF]])
|
||||
# CHECK-NEXT: lit.call {{.*}}__init__{{.*}}([[MREF]])
|
||||
|
||||
# Overwriting is eligible for copy => move optimization as well.
|
||||
var shouldBeMovedFrom = MemExample()
|
||||
# CHECK: lit.call {{.*}}__init__{{.*}}(%shouldBeMovedFrom)
|
||||
cptr[] = shouldBeMovedFrom
|
||||
# CHECK: [[TMP:%.*]] = kgen.rebind %cptr
|
||||
# CHECK-NEXT: [[CP:%.*]] = lit.ref.load [[TMP]]
|
||||
# CHECK-NEXT: lit.var.lifetime.end %cptr
|
||||
# CHECK-NEXT: [[MREF:%.*]] = lit.call {{.*}}__getitem__{{.*}}([[CP]])
|
||||
# CHECK-NEXT: lit.ref.immut
|
||||
# CHECK-NEXT: lit.call {{.*}}__deinit__{{.*}}([[MREF]])
|
||||
# CHECK-NEXT: lit.call {{.*}}__init__{{.*}}move"
|
||||
# CHECK-NEXT: lifetime.end %shouldBeMovedFrom
|
||||
|
||||
# The mutation above could either of A or B, so we needed to extend both of
|
||||
# their origins, but now we can say goodbye.
|
||||
# CHECK-NEXT: lit.call {{.*}}__deinit__{{.*}}(%b)
|
||||
# CHECK-NEXT: lifetime.end %b
|
||||
|
||||
# A use so the assignment isn't dead.
|
||||
a.noop()
|
||||
# CHECK-NEXT: [[ATMP:%.*]] = lit.ref.immut %a
|
||||
# CHECK-NEXT: lit.call {{.*}}noop{{.*}}([[ATMP]])
|
||||
# CHECK-NEXT: lit.call {{.*}}__deinit__{{.*}}(%a)
|
||||
# CHECK-NEXT: lifetime.end %a
|
||||
|
||||
# ===----------------------------------------------------------------------=== #
|
||||
# Tests of the Pointer type.
|
||||
# ===----------------------------------------------------------------------=== #
|
||||
|
||||
# CHECK-LABEL: lit.fn @"testUseConditionalReference
|
||||
|
||||
def testUseConditionalReference(cond: __mlir_type.`!kgen.scalar<bool>`, immArg: MemExample):
|
||||
# CHECK: %a = lit.var.decl {{.*}} : !lit.ref<!MemExample, mut *"a`1">
|
||||
# CHECK: lit.call {{.*}}__init__{{.*}}(%a)
|
||||
|
||||
var a = MemExample()
|
||||
|
||||
# CHECK: lit.call @std::@builtin::@stubs::@Pointer::@"__init__{{.*}}(%a)
|
||||
var aref = Pointer(to=a)
|
||||
# CHECK: lit.alias.decl *"aLifetime{{.*}}": origin<true> = <*"a`1">
|
||||
comptime aLifetime = aref.origin._mlir_origin
|
||||
|
||||
# CHECK-NEXT: [[AR:%.*]] = lit.ref.load %aref
|
||||
# CHECK-NEXT: [[REF:%.*]] = lit.call {{.*}}__getitem__{{.*}}([[AR]])
|
||||
aref[].noop()
|
||||
# CHECK-NEXT: [[IMMREF:%.*]] = lit.ref.immut [[REF]]
|
||||
# CHECK-NEXT: lit.call {{.*}}noop{{.*}}([[IMMREF]])
|
||||
|
||||
# This is a mutable reference so go head and store through it whynot?
|
||||
# CHECK-NEXT: [[AR:%.*]] = lit.ref.load %aref
|
||||
# CHECK-NEXT: [[REF:%.*]] = lit.call {{.*}}__getitem__{{.*}}([[AR]])
|
||||
aref[] = MemExample()
|
||||
# CHECK-NEXT: lit.call {{.*}}__deinit__{{.*}}([[REF]])
|
||||
# CHECK-NEXT: lit.call {{.*}}__init__{{.*}}([[REF]])
|
||||
|
||||
# The reference being alive doesn't keep the underlying stuff alive, only
|
||||
# accesses
|
||||
# CHECK-NEXT: %aref2 = lit.var.decl "aref2"
|
||||
# CHECK-NEXT: [[AR:%.*]] = lit.ref.load %aref
|
||||
# CHECK-NEXT: lifetime.end %aref
|
||||
# CHECK-NEXT: lifetime.start %aref2
|
||||
# CHECK-NEXT: lit.ref.store [[AR]], %aref2
|
||||
# CHECK-NEXT: lifetime.end %aref2
|
||||
# expected-warning @+1 {{assignment to 'aref2' was never used}}
|
||||
var aref2 = aref
|
||||
|
||||
# Ok, this was the last use of A so it can go away.
|
||||
# CHECK-NEXT: lit.call {{.*}}__deinit__{{.*}}(%a)
|
||||
# CHECK-NEXT: lifetime.end %a
|
||||
|
||||
# Pointer can bind to immutable things as well, no problem.
|
||||
# CHECK-NEXT: [[IMMRV:%.*]] = lit.call tail @std::@builtin::@stubs::@Pointer::@"__init__{{.*}}(%immArg)
|
||||
# CHECK-NEXT: %immref = lit.var.decl "immref"
|
||||
# CHECK: lit.ref.store [[IMMRV]], %immref
|
||||
var immref = Pointer(to=immArg)
|
||||
immref[].noop()
|
||||
|
||||
# ===----------------------------------------------------------------------=== #
|
||||
# Test that we can bind self origin.
|
||||
# ===----------------------------------------------------------------------=== #
|
||||
|
||||
# Need a way to get a origin of Self.
|
||||
# https://github.com/modularml/modular/issues/29069
|
||||
|
||||
struct SelfRefTest(ImplicitlyCopyable):
|
||||
def __init__(out self): pass
|
||||
def __deinit__(deinit self): pass
|
||||
# CHECK-LABEL: lit.fn @"method
|
||||
# CHECK-SAME: (%self: !lit.ref<!SelfRefTest
|
||||
def method(ref self) -> Pointer[Self, origin_of(self)]:
|
||||
return Pointer(to=self)
|
||||
|
||||
# CHECK-LABEL: lit.fn @"testSelfRef
|
||||
def testSelfRef(a: SelfRefTest, mut b: SelfRefTest):
|
||||
# Bind immutably to a
|
||||
# CHECK: = lit.call {{.*}}method{{.*}}<:scalar<bool> false, :origin<false> *"a`">(%a)
|
||||
_ = a.method()
|
||||
|
||||
# Bind mutably to b
|
||||
# CHECK: = lit.call {{.*}}method{{.*}}<:scalar<bool> true, :origin<true> *"b`1">(%b)
|
||||
_ = b.method()
|
||||
|
||||
|
||||
# CHECK-LABEL: lit.fn @"testLifetimeOf1
|
||||
# CHECK-SAME: (%a: !lit.ref<!MemExample, imm *"a`"> imm_mem) ->
|
||||
# CHECK-SAME: !lit.struct<#Pointer <{{.*}}:origin<false> *"a`">> {}, :!AddressSpace {_value: !SIMDLength = {0}}>>
|
||||
def testLifetimeOf1(a: MemExample) -> Pointer[MemExample, origin_of(a)]:
|
||||
return Pointer(to=a)
|
||||
|
||||
# CHECK-LABEL: lit.fn @"testLifetimeOf2
|
||||
# CHECK-SAME: (%a: !lit.ref<!MemExample, imm *"a`"> imm_mem) ->
|
||||
# CHECK-SAME: !lit.ref<!MemExample, imm *"a`">
|
||||
def testLifetimeOf2(a: MemExample) -> Pointer[MemExample, origin_of(a)]._mlir_lit_ref:
|
||||
|
||||
# CHECK: kgen.return {{.*}} : !lit.ref<!MemExample, imm *"a`">
|
||||
return __get_mvalue_as_litref(a)
|
||||
|
||||
# CHECK-LABEL: lit.fn @"callByRefResultLifetime
|
||||
def callByRefResultLifetime(mut x: MemExample, mut y: MemExample, z: MemExample):
|
||||
# CHECK: lit.var.decl "l1" var : !lit.ref<{{.*}}(mutcast mut *"x`")
|
||||
var l1 = returnOneArgLifetime(x)
|
||||
|
||||
# CHECK: lit.var.decl "l2" var : !lit.ref<{{.*}}#TwoLifetimes <:origin<false> (mutcast mut *"x`"), :origin<false> (mutcast mut *"y`1"),
|
||||
var l2 = returnTwoArgLifetimes(x, y)
|
||||
# CHECK: %l3 = lit.var.decl "l3" var : !lit.ref<{{.*}}#TwoLifetimes <:origin<false> (mutcast mut *"x`"), :origin<false> (mutcast mut *"x`"),
|
||||
var l3 = returnTwoArgLifetimes(x, x)
|
||||
# CHECK: %l4 = lit.var.decl "l4" var : !lit.ref<{{.*}}#TwoLifetimes <:origin<false> *"z`2", :origin<false> *"z`2",
|
||||
var l4 = returnTwoArgLifetimes(z, z)
|
||||
|
||||
use_any(l1, l2, l3, l4)
|
||||
|
||||
def returnOneArgLifetime(a: MemExample)
|
||||
-> OneLifetime[origin_of(a)]:
|
||||
return OneLifetime[origin_of(a)]()
|
||||
|
||||
def returnTwoArgLifetimes(a: MemExample, b: MemExample)
|
||||
-> TwoLifetimes[origin_of(a), origin_of(b)]:
|
||||
return TwoLifetimes[origin_of(a), origin_of(b)]()
|
||||
|
||||
struct OneLifetime[a_origin: ImmOrigin](Movable where False):
|
||||
def __init__(out self): pass
|
||||
|
||||
struct TwoLifetimes[a_origin: ImmOrigin,
|
||||
b_origin: ImmOrigin](Movable where False):
|
||||
def __init__(out self): pass
|
||||
|
||||
# Test that we can infer the type of 'T' in the func param invocation.
|
||||
# CHECK-LABEL: CutDownVariadicPack
|
||||
struct CutDownVariadicPack[element_trait: type_of(AnyType), //,
|
||||
*element_types: element_trait](Movable where False):
|
||||
|
||||
# CHECK: lit.fn @"each_hack
|
||||
def each_hack[i: Int, func: def[T: Self.element_trait] (T) thin -> None](self):
|
||||
# Test that we can infer the type of 'T' from the argument.
|
||||
# CHECK-NEXT: [[REFVAL:%.*]] = lit.call {{.*}}get_element{{.*}}(%self)
|
||||
# CHECK-NEXT: [[REF:%.*]] = lit.call {{.*}}Pointer::@"__getitem__{{.*}}([[REFVAL]])
|
||||
# CHECK-NEXT: lit.call{{.*}} func,
|
||||
# CHECK-SAME: :!kgen.param<:meta<!AnyType> element_trait> #kgen.param_list.get<:param_list<:meta<!AnyType> element_trait>
|
||||
# CHECK-SAME: element_types{{.*}}([[REF]])
|
||||
func(self.get_element[i]()[])
|
||||
|
||||
def get_element[index: Int](self) -> Pointer[
|
||||
Self.element_types[index],
|
||||
origin_of(self)]:
|
||||
while True: pass
|
||||
|
||||
# Test that you can implicitly convert an "any" mutable reference (as is returned
|
||||
# by Pointer for example) to mortal reference with specified origin.
|
||||
# CHECK: lit.fn @"test_immortal_to_mortal
|
||||
def test_immortal_to_mortal(arg: Pointer[Int, _])
|
||||
-> Pointer[Int, arg.origin]:
|
||||
# CHECK-NEXT: [[ARGREF:%.*]] = lit.call {{.*}}Pointer::@"__getitem__{{.*}}(%arg)
|
||||
# CHECK-NEXT: [[PTRVAL:%.*]] = lit.call {{.*}}Pointer::@"__init__{{.*}}([[ARGREF]])
|
||||
# CHECK-NEXT: [[REF:%.*]] = lit.call {{.*}}Pointer::@"__getitem__{{.*}}([[PTRVAL]])
|
||||
# CHECK-NEXT: [[RES:%.*]] = lit.call {{.*}}@Pointer::@"__init__{{.*}}([[REF]])
|
||||
# CHECK-NEXT: kgen.return [[RES]]
|
||||
return Pointer[Int, arg.origin](to=Pointer(to=arg[])[])
|
||||
|
||||
|
||||
# CHECK-LABEL: lit.fn @"ref_copyability
|
||||
def ref_copyability[*element_types: ImplicitlyCopyable & Deinitable](*args: *element_types):
|
||||
# CHECK: [[ITEM:%.*]] = lit.call tail @std::@builtin::@stubs::@VariadicPack::@"__getitem_param__
|
||||
# CHECK: %_x = lit.var.decl
|
||||
# CHECK: lit.call[!lit.generator<[2](*, "copy"{{.*}}#kgen.get_witness<{{.*}}__init__{{.*}}([[ITEM]], %_x)
|
||||
var _x = args[4]
|
||||
|
||||
# CHECK-NEXT: lit.call[{{.*}}#kgen.get_witness<{{.*}}__deinit__{{.*}}(%_x)
|
||||
|
||||
# Issue #37659: Parameter inference doesn't work with force-immut origins
|
||||
|
||||
# FIXME (Patch #48185): need to support implicit conversions to immutable reference.
|
||||
|
||||
#def thing_taking_immutable_ref[T: AnyType, value_origin: Origin[]](a: Pointer[T, value_origin]): pass
|
||||
#def test_passing_mutable_ref(mut i: String):
|
||||
# thing_taking_immutable_ref(Pointer(to=i))
|
||||
|
||||
# Verify that we can propagate parametric mutability through field accesses.
|
||||
struct ThingWithFields(Movable where False):
|
||||
var field: Int
|
||||
|
||||
# CHECK-LABEL: lit.fn @"parametric_mut_mbvalue
|
||||
def parametric_mut_mbvalue[origin: Origin](a: Pointer[ThingWithFields, origin]) -> Pointer[Int, origin_of(a[].field)]:
|
||||
# CHECK: lit.ref.struct.ger
|
||||
return Pointer(to=a[].field)
|
||||
|
||||
# Pointer directly with inferred params.
|
||||
struct SomeStructWithReferenceSelfArgument(Movable where False):
|
||||
def __init__(out self): pass
|
||||
def hello(ref self):
|
||||
pass
|
||||
|
||||
# CHECK-LABEL: lit.fn @"testMethodRef
|
||||
def testMethodRef(a: SomeStructWithReferenceSelfArgument):
|
||||
# CHECK-NEXT: lit.call {{.*}}@"hello{{.*}}(%a)
|
||||
a.hello()
|
||||
|
||||
|
||||
|
||||
# CHECK-LABEL: lit.fn @"variadic_inout_mems_iter
|
||||
def variadic_inout_mems_iter(mut *mems: MemExample):
|
||||
# Verify the iterator keeps the VariadicList alive.
|
||||
|
||||
# CHECK-NEXT: [[TMP:%.*]] = lit.call {{.*}}__iter__{{.*}}(%mems)
|
||||
# CHECK: %iter = lit.var.decl
|
||||
# CHECK-NEXT: lifetime.start %iter
|
||||
# CHECK-NEXT: lit.ref.store [[TMP]], %iter
|
||||
var iter = mems.__iter__()
|
||||
|
||||
# CHECK-NEXT: %__try_error__ = lit.var.decl
|
||||
# CHECK-NEXT: lit.try
|
||||
|
||||
# CHECK-NEXT: %__call_result_tmp__ = lit.var.decl {{.*}} : !lit.ref<!lit.ref<
|
||||
# CHECK: lit.call {{.*}}__next__{{.*}}(%iter, {{.*}}, %__call_result_tmp__)
|
||||
|
||||
# Iterator is destroyed as soon as we're done with it.
|
||||
# CHECK-NEXT: lifetime.end %iter
|
||||
|
||||
# CHECK: [[ELTREF:%.*]] = lit.load.consume %__call_result_tmp__
|
||||
# CHECK-NEXT: lit.var.lifetime.end %__call_result_tmp__
|
||||
|
||||
# Copy the result of __next__ into !lit.ref
|
||||
# CHECK-NEXT: %x = lit.var.decl
|
||||
# CHECK-NEXT: [[ELTREFIMM:%.*]] = lit.ref.immut [[ELTREF]]
|
||||
# CHECK-NEXT: lifetime.start %x
|
||||
# CHECK-NEXT: lit.call {{.*}}__init__{{.*}}copy"
|
||||
try:
|
||||
var x : MemExample = iter.__next__()
|
||||
|
||||
# CHECK-NEXT: lit.call {{.*}}mutate{{.*}}(%x)
|
||||
x.mutate()
|
||||
except:
|
||||
pass
|
||||
|
||||
# CHECK-NEXT: lit.call {{.*}}__deinit__{{.*}}(%x)
|
||||
# CHECK-NEXT: lifetime.end %x
|
||||
|
||||
|
||||
# CHECK-LABEL: lit.fn @"test_pvalue_ref_formation
|
||||
def test_pvalue_ref_formation[a: SelfRefTest]():
|
||||
# This is invoking a method (accepting a ref) on a pvalue. This need to
|
||||
# materialize into a temporary and use the origin of the temporary, not an
|
||||
# immortal origin.
|
||||
|
||||
# CHECK: [[ANONTMP:%.*]] = lit.var.decl "anonymous*" {{.*}}!lit.ref<!SelfRefTest,
|
||||
var r = a.method()
|
||||
# The result reference should have inferred the origin of the temp
|
||||
# CHECK: lit.ref.store {{.*}}, %r : {{.*}}!SelfRefTest, {{.*}}origin<false> (mutcast mut *"anonymous*`
|
||||
|
||||
# This use of the temp should keep it alive.
|
||||
# CHECK: [[REFERENCE:%.*]] = lit.ref.load %r
|
||||
# CHECK: [[REF:%.*]] = lit.call {{.*}}Pointer::@"__getitem__{{.*}}([[REFERENCE]])
|
||||
# CHECK-NEXT: lit.call {{.*}}method{{.*}}([[REF]])
|
||||
_ = r[].method()
|
||||
# CHECK-NEXT: lit.call {{.*}}SelfRefTest::@"__deinit__{{.*}}([[ANONTMP]])
|
||||
|
||||
# MOCO-1025 - Need hierarchical origins
|
||||
struct FieldRefPropagation(Movable where False):
|
||||
var field1 : Optional[Int]
|
||||
var field2 : Int
|
||||
|
||||
def __init__(out self):
|
||||
# Should be able to initialize field1 and use it.
|
||||
self.field1 = 42
|
||||
# Should be able to project it and assign through ref.
|
||||
self.field1.value() = 17
|
||||
# Then initialize field2
|
||||
self.field2 = 1
|
||||
|
||||
|
||||
# Issue #3444 (nightly) Raising init causing use of uninitialized variable
|
||||
# https://github.com/modular/mojo/issues/3444
|
||||
struct HasRaisingInit(Copyable):
|
||||
def __init__(out self) raises: pass
|
||||
|
||||
struct ImmovableRaisingInit(Movable where False):
|
||||
def __init__(out self) raises: pass
|
||||
|
||||
struct RaisingInitWrapper(Movable where False):
|
||||
var field: HasRaisingInit
|
||||
var immfield: ImmovableRaisingInit
|
||||
|
||||
def __init__(out self) raises:
|
||||
self.field = HasRaisingInit()
|
||||
self.immfield = ImmovableRaisingInit()
|
||||
|
||||
# CHECK-LABEL: lit.fn @"test_inout_raising_init
|
||||
def test_inout_raising_init(mut a: HasRaisingInit, mut b: RaisingInitWrapper) raises:
|
||||
# These init calls need a temporary instead of direct assignment into the dest
|
||||
# to avoid invalidating a value on the error path.
|
||||
# CHECK-NEXT: [[TEMP:%.*]] = lit.var.decl
|
||||
# CHECK: lit.call {{.*}}HasRaisingInit::@"__init__{{.*}}({{.*}}, [[TEMP]])
|
||||
a = HasRaisingInit()
|
||||
# EH logic.
|
||||
# CHECK: lit.call {{.*}}HasRaisingInit::@"__init__{{.*}}move"
|
||||
|
||||
# CHECK: [[FIELDREF:%.*]] = lit.ref.struct.ger %b[field]
|
||||
# CHECK: [[TEMP:%.*]] = lit.var.decl
|
||||
# CHECK: lit.call {{.*}}HasRaisingInit::@"__init__{{.*}}({{.*}}, [[TEMP]])
|
||||
b.field = HasRaisingInit()
|
||||
# EH logic.
|
||||
# CHECK: lit.call {{.*}}HasRaisingInit::@"__init__{{.*}}(*, "move":
|
||||
|
||||
# CHECK-LABEL: lit.fn @"test_parameter_closure_captures
|
||||
def test_parameter_closure_captures(var x: MemExample, var y: MemExample):
|
||||
# CHECK: lit.fn *"capture
|
||||
@__parameter
|
||||
def capture():
|
||||
_ = x^
|
||||
_ = y^
|
||||
|
||||
# CHECK: lit.call[!lit.generator<:{mut *"x`{{.*}}", mut *"y`{{.*}}"}:
|
||||
# CHECK-NEXT: lit.call {{.*}}MemExample::@"__deinit__{{.*}}(%y)
|
||||
# CHECK-NEXT: lit.call {{.*}}MemExample::@"__deinit__{{.*}}(%x)
|
||||
capture()
|
||||
|
||||
def higher_order_function[lts: __mlir_type.`!lit.origin.set`, //, f: def() capturing [lts] -> None]():
|
||||
pass
|
||||
|
||||
# CHECK-LABEL: lit.fn @"test_higher_order_capture
|
||||
def test_higher_order_capture(var x: MemExample, var y: MemExample):
|
||||
# CHECK: lit.fn *"capture
|
||||
@__parameter
|
||||
def capture():
|
||||
_ = x^
|
||||
_ = y^
|
||||
|
||||
# CHECK: lit.call {{.*}}higher_order_function{{.*}} !lit.generator<:{mut *"x`{{.*}}", mut *"y`{{.*}}"}
|
||||
# CHECK-NEXT: lit.call {{.*}}MemExample::@"__deinit__{{.*}}(%y)
|
||||
# CHECK-NEXT: lit.call {{.*}}MemExample::@"__deinit__{{.*}}(%x)
|
||||
higher_order_function[capture]()
|
||||
|
||||
# CHECK-LABEL: lit.fn @"test_origin_ref_spec
|
||||
# CHECK-SAME: !lit.ref<!Int, mut *"our_origin._mlir_origin`"> mutref)
|
||||
def test_origin_ref_spec[our_origin: Origin[mut=True]](ref[our_origin] a: Int):
|
||||
pass
|
||||
|
||||
# CHECK-LABEL: lit.fn @"another_min
|
||||
def another_min[mut: Bool, //, ao: Origin[mut=mut], bo: Origin[mut=mut]](ref [ao]a: Int, ref [bo]b: Int) -> ref [a, b] Int:
|
||||
if a < b:
|
||||
return a
|
||||
else: # This failed due to union canonicalization problems.
|
||||
return b
|
||||
|
||||
struct RefResultStruct(Movable where False):
|
||||
var x: Int
|
||||
def __init__(out self): self.x = 1
|
||||
def method(self) -> ref [self.x] Int: return self.x
|
||||
|
||||
# https://github.com/modular/mojo/issues/3960
|
||||
# CHECK-LABEL: lit.struct.decl @FieldSensitiveUse
|
||||
struct FieldSensitiveUse(Movable where False):
|
||||
var x: RefResultStruct
|
||||
var y: String
|
||||
|
||||
# CHECK: lit.fn @"__init__
|
||||
def __init__(out self):
|
||||
# CHECK: lit.call {{.*}}RefResultStruct::@"__init__
|
||||
self.x = RefResultStruct()
|
||||
# CHECK: [[TMP:%.*]] = lit.call {{.*}}RefResultStruct::@"method
|
||||
_ = self.x.method()
|
||||
# CHECK-NEXT: lit.ownership.use [[TMP]]
|
||||
self.y = String()
|
||||
# CHECK-NEXT: [[TMP:%.*]] = lit.ref.struct.ger %self[y]
|
||||
# CHECK-NEXT: lit.call {{.*}}String::@"__init__{{.*}}([[TMP]])
|
||||
|
||||
|
||||
# MOCO-2077: https://github.com/modular/modular/issues/4705
|
||||
# CHECK-LABEL: lit.fn @"test_getitem_setitem
|
||||
def test_getitem_setitem(mut d: TestDict[Int, Int]):
|
||||
# This should bind to a mutable reference, not an immutable one.
|
||||
# CHECK: %0 = lit.call {{.*}}@TestDict::@"__getitem__
|
||||
# CHECK: lit.call {{.*}}@"check_mutability{{.*}}<:!Bool {:scalar<bool> true}, {{.*}}(%0)
|
||||
check_mutability(d[])
|
||||
|
||||
|
||||
def check_mutability[
|
||||
is_mutable: Bool, //, origin: Origin[mut=is_mutable], T: AnyType
|
||||
](ref [origin]s: T):
|
||||
pass
|
||||
|
||||
|
||||
struct TestDict[K: AnyType, V: Deinitable](Movable where False):
|
||||
def __getitem__(ref self) -> ref [self] Self.V:
|
||||
while True: pass
|
||||
|
||||
def __setitem__(mut self, var value: Self.V):
|
||||
pass
|
||||
|
||||
# ===----------------------------------------------------------------------=== #
|
||||
# Interior origins
|
||||
# ===----------------------------------------------------------------------=== #
|
||||
|
||||
struct MyListInterior[T: Movable](Movable where False):
|
||||
var data: UnsafePointer[Self.T, UntrackedOrigin[mut=True]]
|
||||
|
||||
def __init__(out self):
|
||||
self.data = UnsafePointer[Self.T, UntrackedOrigin[mut=True]].unsafe_dangling()
|
||||
|
||||
def __deinit__(deinit self):
|
||||
pass # Explicit deinit so it isn't considered trivial and elided.
|
||||
|
||||
def mutate(mut self):
|
||||
pass
|
||||
|
||||
def __getitem__(
|
||||
ref self
|
||||
) -> ref[self.data._get_ref_with_unsafe_interior_origin["element"](self)] Self.T:
|
||||
return (self.data)._get_ref_with_unsafe_interior_origin["element"](self)
|
||||
|
||||
# CHECK-LABEL: lit.fn @"test_interior0
|
||||
def test_interior0():
|
||||
# CHECK: lit.call {{.*}}MyListInterior::@"__init__
|
||||
var list = MyListInterior[Int]()
|
||||
# CHECK: lit.call {{.*}}MyListInterior::@"__getitem__
|
||||
ref elt = list[]
|
||||
# CHECK: lit.call {{.*}}SIMD::@"__iadd__
|
||||
elt += 4
|
||||
# CHECK: lit.call {{.*}}MyListInterior::@"__deinit__
|
||||
|
||||
# ===----------------------------------------------------------------------=== #
|
||||
# Subtree origins
|
||||
# ===----------------------------------------------------------------------=== #
|
||||
|
||||
trait MyIndexable:
|
||||
def __getitem__(ref self, idx: Int) -> ref[origin_of(self).subtree] Int:
|
||||
...
|
||||
|
||||
struct MyList(MyIndexable):
|
||||
var elements: List[Int]
|
||||
|
||||
# More concrete origin so concrete clients get a tighter origin bound.
|
||||
def __getitem__(ref self, idx: Int) -> ref[self.elements[idx]] Int:
|
||||
return self.elements[idx]
|
||||
|
||||
def test_MyIndexable(mut idxable: Some[MyIndexable]):
|
||||
_ = idxable[0]
|
||||
idxable[0] += 1
|
||||
|
||||
def test_subtree(mut mylist: MyList):
|
||||
test_MyIndexable(mylist)
|
||||
|
||||
# MOCO-4453: Tests for origin union collapsing.
|
||||
struct OriginWhereClauseTest:
|
||||
var f: Int
|
||||
|
||||
def __init__(out self):
|
||||
self.f = 0
|
||||
|
||||
def field_in_subtree(ref self) where origin_of(self).subtree.contains[origin_of(self.f)]:
|
||||
pass
|
||||
def field_subtree_in_subtree(ref self) where origin_of(self).subtree.contains[origin_of(self.f).subtree]:
|
||||
pass
|
||||
|
||||
def test_origin_where_clause():
|
||||
var s = OriginWhereClauseTest()
|
||||
s.field_in_subtree()
|
||||
s.field_subtree_in_subtree()
|
||||
Reference in new issue
Block a user