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

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

No files matched your search

@@ -0,0 +1,132 @@
# ===----------------------------------------------------------------------=== #
# 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 -verify-diagnostics %s
##===----------------------------------------------------------------------===##
# comptime assert errors
##===----------------------------------------------------------------------===##
struct NotBool(Movable where False):
pass
def test_non_bool_type_error[x: NotBool]():
# expected-error @below {{'NotBool' does not implement the '__bool__' method}}
comptime assert x
def test_runtime_expr_error(x: Int, y: Int):
# expected-error @below {{cannot use a dynamic value in 'comptime assert' expression}}
comptime assert x == y
def test_non_string_literal_message_error():
# expected-error @below {{cannot implicitly convert}}
comptime assert True, 42
struct Notdef[x: Bool](Movable where False):
# expected-error @below {{'comptime assert' must be inside a function; move this into a function body}}
comptime assert x
# expected-note @below {{cannot prove constraint}}
# expected-note @below {{constraint declared here}}
# expected-note @below {{function declared here}}
def requires_natural[x: Int]() where x >= 0:
pass
def requires_not_natural[x: Int]() where not (x >= 0):
pass
def requires_positive[x: Int]() where x > 0:
pass
def requires_not_positive[x: Int]() where not (x > 0):
pass
def requires_zero[x: Int]() where x == 0:
pass
def requires_not_zero[x: Int]() where not (x == 0):
pass
def test_assert_injects_assumption_correctly[x: Int]():
comptime if x > 10:
comptime assert x >= 0
# This is OK.
requires_natural[x]()
else:
# expected-error @below {{invalid call to 'requires_natural': lacking evidence to prove correctness}}
# expected-note @below {{provide evidence for the constraint here to aid in candidate selection}}
requires_natural[x]()
# expected-error @below {{invalid call to 'requires_natural': lacking evidence to prove correctness}}
# expected-note @below {{provide evidence for the constraint here to aid in candidate selection}}
requires_natural[x]()
# COM: MOCO-3725: the else branch must not inherit the positive condition.
# COM: The else branch gets NOT(x >= 0) as an assumption, which contradicts the
# COM: `where x >= 0` constraint, so the call is "violated", not "unprovable".
def test_else_branch_does_not_leak_then_assumption[x: Int]():
comptime if x >= 0:
requires_natural[x]()
else:
# expected-error @below {{invalid call to 'requires_natural': violated constraint}}
requires_natural[x]()
def test_else_branch_can_use_inverse_constraint[x: Int]():
comptime if x >= 0:
requires_natural[x]()
else:
requires_not_natural[x]()
# COM: Nested comptime-if lowering should accumulate prior false assumptions.
def test_multibranch_branch_assumptions[x: Int]():
comptime if x > 0:
requires_positive[x]()
elif x == 0:
requires_not_positive[x]()
requires_zero[x]()
else:
requires_not_positive[x]()
requires_not_zero[x]()
def test_newly_created_scope[x: Int]():
# expected-error @below {{invalid call to 'requires_natural': lacking evidence to prove correctness}}
# expected-note @below {{provide evidence for the constraint here to aid in candidate selection}}
comptime y = requires_natural[x]()
# COM: This assert should not validate the above statement.
comptime assert x >= 0
def test_always_false_no_warning():
comptime assert 2 < 1
def test_always_true_no_warning():
comptime assert 2 > 1
@@ -0,0 +1,214 @@
# ===----------------------------------------------------------------------=== #
# 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 -verify-diagnostics %s
##===----------------------------------------------------------------------===##
# Return
##===----------------------------------------------------------------------===##
def foo() raises:
# expected-error @+1 {{unexpected token in expression}}
return pass
return 32 # expected-error {{'return' must be inside a function; move this into a function body}}
##===----------------------------------------------------------------------===##
# If / While
##===----------------------------------------------------------------------===##
def elif_parse_error(a: Bool) raises:
if a:
pass
# expected-error @+1 {{unexpected token in expression}}
elif a: # expected-error {{statement indentation must match the rest of the block; adjust to align}}
pass
else:
pass
struct NotBoolConvertible(Movable where False):
def __init__(out self, *, copy: Self):
pass
def test_bool_context(a: NotBoolConvertible) raises:
if a: # expected-error {{NotBoolConvertible' does not implement the '__bool__' method}}
pass
def test_if_decorator(a: Bool):
@not_good()
if a: # expected-error {{'if' statement does not support decorators; remove the decorator}}
pass
comptime if 1:
pass
elif a: # expected-error {{cannot use a dynamic value in 'comptime if' condition}}
pass
def test_comptime_if_dynamic_elif(a: Bool):
comptime if 1:
pass
elif a: # expected-error {{cannot use a dynamic value in 'comptime if' condition}}
pass
def test_decorator_with_comptime_if():
@not_good()
comptime if True: # expected-error {{'comptime if' statement does not support decorators; remove the decorator}}
pass
def test_comptime_elif_not_allowed(a: Bool):
if a:
pass
comptime elif a: # expected-error {{'comptime' cannot be used with 'elif'}}
pass
##===----------------------------------------------------------------------===##
# For
##===----------------------------------------------------------------------===##
struct my_iter_no_next(Movable where False):
def __init__(out self): pass
struct MyList_range_no_next(Movable where False):
def __init__(out self): pass
def __iter__(self) -> my_iter_no_next: return my_iter_no_next()
struct MyList_no_iter(Movable where False):
def __init__(out self): pass
@fieldwise_init
struct MyFloat(Movable where False):
pass
def test():
var my_list_no_next = MyList_range_no_next()
var my_list_no_iter = MyList_no_iter()
# The failed 'Iterable' conformance makes this target an ordinary
# assignment, so it declares and needs the 'var'. The two loops below
# reach no such check: one has no '__iter__', the other a tuple target.
# expected-error @+2 {{'my_iter_no_next' does not conform to 'Iterable'; add conformance to use in a 'for' loop}}
# expected-note @+1 {{to conform to 'Iterable', add it to the struct declaration: 'struct Foo(Iterable):'}}
for var item in my_list_no_next:
pass
# expected-error @+1 {{'MyList_no_iter' does not implement the '__iter__' method}}
for var item in my_list_no_iter:
pass
# expected-error @+2 {{'my_iter_no_next' does not conform to 'Iterable'; add conformance to use in a 'for' loop}}
# expected-note @+1 {{to conform to 'Iterable', add it to the struct declaration: 'struct Foo(Iterable):'}}
for var key, item in my_list_no_next:
pass
# Issue #18599
def spurious_for_loop_variable_unknown_decl():
# expected-error @below {{'FloatLiteral[1]' does not implement the '__iter__' method}}
for i in 1.0:
# Note that the bug in issue #18599 is that after the above error, another error
# will be spuriously raised about i not being bound. So the real check in
# this test is that no further error is raised.
_ = i
struct ListValueInt(Movable where False):
def __init__(out self): pass
def __iter__(self) -> ListValueInt: return ListValueInt()
def __next__(mut self) raises StopIteration -> Int: return 0
struct ListValueStringRef(Movable where False):
def __init__(out self): pass
def __iter__(self) -> ListValueStringRef: return ListValueStringRef()
def __next__(mut self) raises StopIteration -> ref [self] String: pass
def loop_variable_scoped() raises:
for i in ListValueInt():
i = i # expected-error {{expression must be mutable in assignment}}
_ = i # expected-error {{use of unknown declaration 'i'}}
for elt in ListValueStringRef():
elt = "foo" # expected-error {{expression must be mutable in assignment}}
for ref elt in ListValueStringRef():
elt = "foo" # ok
##===----------------------------------------------------------------------===##
# With
##===----------------------------------------------------------------------===##
struct ExampleCM(Movable):
def __enter__(self) -> Int:
return 42
def __exit__(self):
pass # normal
def __exit__(self, err: Error) -> Bool:
return True # Raise
def withUsingImmutableVariable(var a: ExampleCM) raises:
var x = 77
with a^ as x:
pass
# External Issue #529 https://github.com/modular/mojo/issues/529
def withWithNoColon(var a: ExampleCM) raises:
# expected-error @below {{expected ':' or ',' after 'with' expression}}
with a^ as b
def withNoRaise(var mgr: ExampleCM):
with mgr^:
# expected-error @below {{'raise' requires a surrounding 'try' block or the enclosing function to declare 'raises'}}
raise Error()
# Allow try-finally, but in a non-raising region.
try:
# expected-error @below {{'raise' requires a surrounding 'try' block or the enclosing function to declare 'raises'}}
raise Error()
finally:
pass
# Poor error when with context managers that take ownership in enter
# https://github.com/modularml/modular/issues/23100
struct BadCM(Movable where False): # expected-note {{'BadCM' declared here}}
def __init__(out self): pass
def __enter__(var self) -> Int:
return 42
def __exit__(self):
pass # normal
def __exit__(self, err: Error) -> Bool:
return True # Raise
def noop(a: Int): pass
def testBadCM():
# expected-error @+1 {{context manager of type 'BadCM' defines a consuming __enter__ method as well as an __exit__ method; either remove 'var' from its '__enter__' method or remove the '__exit__' method}}
with BadCM():
pass
struct MyBool(TrivialRegisterPassable):
var _mlir_value: __mlir_type.`!kgen.scalar<bool>`
# expected-note @below {{function declared here}}
def __mlir_bool__(self) -> __mlir_type.`!kgen.scalar<bool>`:
return self._mlir_value
def noIndentError():
for i in ListValueInt():
# expected-error @+1 {{value passed to 'self' cannot be converted from type value 'MyBool' to an instance of 'MyBool'; did you mean to instantiate 'MyBool'?}}
if MyBool: # no error 'statements must start at the beginning of a line' should be printed
pass
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,712 @@
# ===----------------------------------------------------------------------=== #
# 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 -verify-diagnostics %s
def match_bad_subject_skips_same_indent_cases():
# expected-error @+1 {{use of unknown declaration 'no_such_subject'}}
match no_such_subject:
case 0:
pass
case 1 if True:
pass
# Recovery must resume here, not leave a dangling 'case' for the outer suite.
# expected-error @+1 {{use of unknown declaration 'also_missing'}}
_ = also_missing
def match_bad_subject_skips_indented_cases():
# expected-error @+1 {{use of unknown declaration 'no_such_subject'}}
match no_such_subject:
case 0:
pass
case _:
pass
# expected-error @+1 {{use of unknown declaration 'also_missing'}}
_ = also_missing
def match_missing_cases(x: Int):
# expected-error @+1 {{'match' statement must have at least one 'case' block}}
match x:
match x:
case foo(): # expected-error {{use of unknown declaration 'foo'}}
pass
# expected-error @+1 {{'match' must be contained in a function}}
match 1:
case 0:
pass
def various_match_issues(a: Int, point: Tuple[Int, Int], value: String):
match a:
case 0:
var x = 42
case _:
# expected-error @+1 {{use of unknown declaration 'x'}}
_ = x
match point:
# expected-error @+1 {{cannot match value of 'Tuple[Int, Int]' of 2 elements against a pattern with 3 elements}}
case (0, 0, 0):
pass
case _:
pass
match point:
# expected-error @+2 {{invalid redefinition of 'x'}}
# expected-note @+1 {{previous definition here}}
case (var x, var x):
pass
# expected-warning @+1 {{case is unreachable; previous cases cover every value of the match subject}}
case _:
pass
# Nested var/ref patterns should warn.
match value:
# expected-warning @+1 {{nested 'var' or 'ref' patterns are redundant, remove the outer pattern}}
case var ref x:
_ = x.byte_length()
match value:
# expected-warning @+1 {{nested 'var' or 'ref' patterns are redundant}}
case ref var y:
_ = y.byte_length()
match a:
# expected-error @+1 {{expected a name after 'as'}}
case 0 as 1:
pass
case _:
pass
match point:
# expected-error @+1 {{expected a name after 'as'}}
case (0 as 1, 2):
pass
case _:
pass
match Int():
# expected-error @+1 {{value of type 'Int' doesn't have a memory origin in 'ref' binding}}
case ref z:
pass
match a:
# expected-error @+1 {{expected a tuple type to match against, got 'Int'}}
case 0 | (1, 2):
pass
case _:
pass
def match_or_pattern_binding_diags(var point: Tuple[Int, Int],
mixed: Tuple[Int, String]):
# Binding only on the left alternative.
match point:
# expected-error @+1 {{or-pattern alternatives must bind the same names; 'x' is bound in one alternative but not the other}}
case (0, var x) | (1, 2):
pass
case _:
pass
# Binding only on the right alternative.
match point:
# expected-error @+1 {{or-pattern alternatives must bind the same names; 'x' is bound in one alternative but not the other}}
case (0, 1) | (var x, 2):
pass
case _:
pass
# Same name, but `var` vs `ref`.
match point:
# expected-error @+1 {{or-pattern binding 'x' must use the same 'var'/'ref' kind in each alternative}}
case (0, var x) | (ref x, 1):
pass
case _:
pass
# Different binding names across alternatives.
match point:
# expected-error @+1 {{or-pattern alternatives must bind the same names; 'x' is bound in one alternative but not the other}}
case (var x, 0) | (var y, 1):
pass
case _:
pass
# Different number of bindings. Leading literals keep both arms live so
# the or does not constant-fold away the RHS. The RHS is irrefutable, so
# the trailing `_` is unreachable.
match point:
# expected-error @+1 {{or-pattern alternatives must bind the same names}}
case (0, var x) | (var x, var y):
pass
# expected-warning @+1 {{case is unreachable; previous cases cover every value of the match subject}}
case _:
pass
# Same name and kind, but incompatible types (String vs Int).
# `(var x, _)` is irrefutable, so the trailing `_` is unreachable.
match mixed:
# expected-error @+2 {{or-pattern binding 'x' has incompatible types across alternatives}}
# expected-note @+1 {{first alternative has type 'String', this alternative has type 'Int'}}
case (0, var x) | (var x, _):
pass
# expected-warning @+1 {{case is unreachable; previous cases cover every value of the match subject}}
case _:
pass
@fieldwise_init
struct Vec3:
var x: Int
var y: Int
var z: Int
def match_struct_pattern_diags(v: Vec3):
match v:
# expected-error @+1 {{cannot match value of type 'Vec3' against pattern type 'Int'}}
case Int(x=0):
pass
case _:
pass
match v:
# expected-error @+1 {{'w' is not a field of 'Vec3'}}
case Vec3(w=0):
pass
case _:
pass
match v:
# expected-error @+2 {{keyword argument 'x' was already used; remove the duplicate}}
# expected-note @+1 {{previously specified here}}
case Vec3(x=0, x=1):
pass
case _:
pass
match v:
# expected-error @+1 {{struct patterns do not support positional or unpacked arguments}}
case Vec3(0, y=1):
pass
case _:
pass
match v:
# expected-error @+1 {{struct patterns do not support positional or unpacked arguments}}
case Vec3(x=0, *y):
pass
case _:
pass
match v:
# expected-error @+1 {{struct patterns do not support positional or unpacked arguments}}
case Vec3(x=0, **y):
pass
case _:
pass
def match_empty_struct_pattern(s: String):
match s:
# expected-warning @+1 {{struct pattern without subpatterns does not test anything; replace it with '_'}}
case String():
pass
def match_enum_pattern_diags(opt: Optional[Int], someEnum: Some[EnumLike]):
# No-payload cases must be written without parentheses.
match opt:
# expected-error @+1 {{enum case 'None' has no associated value}}
case Optional.None():
pass
case _:
pass
# Cannot destructure a case whose payload is NoneType.
match opt:
# expected-error @+1 {{enum case 'None' has no associated value}}
case Optional.None(value):
pass
case _:
pass
# Payload cases require a subpattern inside the parentheses.
match opt:
# expected-error @+1 {{enum case 'Some' requires a payload pattern inside the parentheses}}
case Optional.Some():
pass
case _:
pass
# Unknown case name (attribute form).
match opt:
# expected-error @+1 {{'Nope' is not a case of 'Optional[Int]'}}
case Optional.Nope:
pass
case _:
pass
# Unknown case name (call form).
match opt:
# expected-error @+1 {{'Nope' is not a case of 'Optional[Int]'}}
case Optional.Nope(ref x):
pass
case _:
pass
# Can only pattern match on concrete types.
match someEnum:
case .What: # expected-error {{cannot match on a parametric enum type}}
pass
@fieldwise_init
struct BoolPair:
var a: Bool
var b: Bool
struct OpenColor(ImplicitlyCopyable, EnumLike):
comptime _enum_case_names = ParameterList.of[
"red".value, "green".value
].values
comptime _enum_case_types = TypeList.of[
Trait=AnyType, NoneType, NoneType
].values
comptime _enum_is_exhaustive = False
def __init__(out self):
pass
def _get_enum_discriminant(self) -> Int:
return 0
def _unsafe_get_enum_payload[
id: Int
](ref self) -> ref[self] TypeList[Self._enum_case_types]()[id]:
while True:
pass
struct ParametricExhaustivityColor[
is_exhaustive: Bool
](ImplicitlyCopyable, EnumLike):
comptime _enum_case_names = ParameterList.of[
"red".value, "green".value
].values
comptime _enum_case_types = TypeList.of[
Trait=AnyType, NoneType, NoneType
].values
comptime _enum_is_exhaustive = Self.is_exhaustive
def __init__(out self):
pass
def _get_enum_discriminant(self) -> Int:
return 0
def _unsafe_get_enum_payload[
id: Int
](ref self) -> ref[self] TypeList[Self._enum_case_types]()[id]:
while True:
pass
def match_open_enum_duplicate(color: OpenColor):
match color:
case .red:
pass
# expected-warning @+1 {{case is unreachable; 'red' is already covered by a previous case}}
case .red:
pass
def match_parametric_exhaustivity[is_exhaustive: Bool](
color: ParametricExhaustivityColor[is_exhaustive]
):
# expected-error @+1 {{'_enum_is_exhaustive' must be statically known when matching an EnumLike type}}
match color:
case .red:
pass
def match_exhaustivity_diags(flag: Bool, opt: Optional[Int], pair: BoolPair):
# Bool is EnumLike: True/False must both be covered (or a catch-all used).
match flag: # expected-warning {{'match' is not exhaustive; missing case for 'False'}}
case True: pass
# Duplicate Bool case after the type is fully covered.
match flag:
case True: pass
case False: pass
# expected-warning @+1 {{case is unreachable; previous cases cover every value of the match subject}}
case _:
pass
# Unreachable arms are still type-checked (body IR is emitted, then
# discarded and replaced with `hlcf.unreachable`).
match flag:
case True: pass
case False: pass
# expected-warning @+1 {{case is unreachable; previous cases cover every value of the match subject}}
case _:
# expected-error @+1 {{use of unknown declaration 'not_a_real_name'}}
_ = not_a_real_name
# Exhaustive Bool×Bool via correlated wildcards.
match flag, flag:
case True, True: pass
case False, True: pass
case _, False: pass
# expected-warning @+1 {{case is unreachable; previous cases cover every value of the match subject}}
case _:
pass
# Non-exhaustive product: (False, False) is missing.
match flag, flag: # expected-warning {{'match' is not exhaustive; missing case for 'False, False'}}
case True, True: pass
case False, True: pass
case True, False: pass
# Parenthesized tuple subject is the same product space of course.
match (flag, ((((flag))))):
case (True, _): pass
case (False, True): pass
case (False, False): pass
# Struct of EnumLike fields: same flattened product; omitted fields are
# wildcards (`b=False` covers both values of `a`).
match pair:
case BoolPair(a=True, b=True): pass
case BoolPair(a=False, b=True): pass
case BoolPair(b=False): pass
# expected-warning @+1 {{case is unreachable; previous cases cover every value of the match subject}}
case _:
pass
# Or of root constructors covers each alternative (union).
match flag:
case True | False: pass
# expected-warning @+1 {{case is unreachable; previous cases cover every value of the match subject}}
case _:
pass
# Or that only covers one ctor is not exhaustive.
match flag: # expected-warning {{'match' is not exhaustive; missing case for 'False'}}
case True | True: pass
# Or in a product: each alternative covers its cells.
match flag, flag:
case (True, _) | (False, False): pass
case (False, True): pass
# expected-warning @+1 {{case is unreachable; previous cases cover every value of the match subject}}
case _:
pass
# Or with a catch-all arm closes the space.
match flag:
case True | _: pass
# expected-warning @+1 {{case is unreachable; previous cases cover every value of the match subject}}
case False:
pass
# Redundant Or after the subject is already covered.
match flag:
case True: pass
case False: pass
# expected-warning @+1 {{case is unreachable; previous cases cover every value of the match subject}}
case True | False:
pass
# Various enum cases.
match opt: # expected-warning {{'match' is not exhaustive; missing case for 'None'}}
case Optional.Some(_):
pass
match opt: # expected-warning {{'match' is not exhaustive; missing case for 'Some'}}
case Optional.None:
pass
# Duplicate Optional case while another constructor is still open.
match opt:
case Optional.Some(_):
pass
# expected-warning @+1 {{'Some' is already covered by a previous case}}
case Optional.Some(x):
_ = x
case Optional.None:
pass
# A payload refinement does not cover the whole enum case.
match opt: # expected-warning {{'match' is not exhaustive; missing case for 'Some'}}
case Optional.Some(0):
pass
case Optional.None:
pass
# A later irrefutable payload pattern covers the rest of `Some`.
match opt:
case Optional.Some(0):
pass
case Optional.Some(_):
pass
case Optional.None:
pass
# Products larger than kMaxProductCells (1024) cannot be tracked cell-by-cell
# (Bool^11 == 2048); require a catch-all instead of silent Opaque.
# expected-warning @+1 {{'match' is too complex to check for exhaustivity; add a '_' case}}
match (
flag,
flag,
flag,
flag,
flag,
flag,
flag,
flag,
flag,
flag,
flag,
):
case True, True, True, True, True, True, True, True, True, True, True:
pass
# A catch-all satisfies the TooComplex requirement.
match (
flag,
flag,
flag,
flag,
flag,
flag,
flag,
flag,
flag,
flag,
flag,
):
case True, True, True, True, True, True, True, True, True, True, True:
pass
case _:
pass
def match_exhaustivity_literal_subjects(n: Int, s: String):
# Int/String are open universes: covering literals never proves exhaustivity,
# but duplicate / already-covered literal cases are diagnosed.
match n:
case 0:
pass
case 1:
pass
match s:
case "a":
pass
case "b":
pass
match s:
case "a":
pass
# expected-warning @+1 {{case is unreachable; '"a"' is already covered by a previous case}}
case "a":
pass
match n:
case 0:
pass
# expected-warning @+1 {{case is unreachable; '0' is already covered by a previous case}}
case 0:
pass
case 1:
pass
# Or of literals covers each alternative; a later duplicate is unreachable.
match n:
case 0 | 1 | 2:
pass
# expected-warning @+1 {{case is unreachable; '1' is already covered by a previous case}}
case 1:
pass
# After a catch-all, everything else is unreachable (still no exhaustivity
# warning when only literals are present).
match n:
case 0:
pass
case _:
pass
# expected-warning @+1 {{case is unreachable; previous cases cover every value of the match subject}}
case 1:
pass
def match_exhaustivity_names_every_missing_case(flag: Bool, pair: BoolPair):
# Guarded cases never count, so both `Bool` cases are still open.
# expected-warning @+1 {{'match' is not exhaustive; missing cases for 'False' and 'True'}}
match flag:
case True if flag: pass
# A product subject lists every open combination.
# expected-warning @+1 {{'match' is not exhaustive; missing cases for 'False, True' and 'True, False'}}
match pair:
case BoolPair(a=True, b=True): pass
case BoolPair(a=False, b=False): pass
# Three or more missing values are listed with a serial comma.
# expected-warning @+1 {{'match' is not exhaustive; missing cases for 'False, False', 'False, True', and 'True, False'}}
match pair:
case BoolPair(a=True, b=True): pass
def match_exhaustivity_summarizes_many_missing_cases(
flags: Tuple[Bool, Bool, Bool, Bool],
):
# expected-warning @+1 {{, and 7 more}}
match flags:
case (True, True, True, True): pass
def comptime_match_or_binding_name_mismatch[x: Tuple[Int, Int]]():
comptime match x:
# expected-error @+1 {{or-pattern alternatives must bind the same names; 'y' is bound in one alternative but not the other}}
case (0, y) | (1, 2):
pass
def comptime_match_var_binding_rejected[x: Int]():
comptime match x:
case var y: # expected-error {{'var' bindings are not supported in 'comptime match'}}
pass
def comptime_match_ref_binding_rejected[x: Int]():
comptime match x:
case ref y: # expected-error {{'ref' bindings are not supported in 'comptime match'}}
pass
def comptime_match_unreachable_body_still_diagnosed[flag: Bool]():
# Unreachable arms are still parsed so body errors are reported.
comptime match flag:
case True:
pass
case False:
pass
# expected-warning @+1 {{case is unreachable; previous cases cover every value of the match subject}}
case _:
# expected-error @+1 {{use of unknown declaration 'no_such_name'}}
_ = no_such_name
def comptime_match_unreachable_after_catchall[x: Int]():
comptime match x:
case _:
pass
# expected-warning @+1 {{case is unreachable; previous cases cover every value of the match subject}}
case 1:
# expected-error @+1 {{use of unknown declaration 'also_missing'}}
_ = also_missing
# MOCO-4946: execution crashed with match
def match_enum_with_payload_not_cover(a: Optional[Int]):
match a:
case .Some(0):
pass
case .Some(_):
pass
case .None:
pass
match a:
case .Some(_):
pass
# expected-warning @+1 {{case is unreachable; 'Some' is already covered by a previous case}}
case .Some(0):
pass
case .None:
pass
def match_product_enum_payload_coverage(a: Tuple[Optional[Int], Bool]):
match a:
case (.Some(_), True):
pass
# expected-warning @+1 {{case is unreachable; previous cases cover every value of the match subject}}
case (.Some(0), True):
pass
case _:
pass
match a:
case (.Some(0), True):
pass
case (.Some(_), True):
pass
case _:
pass
def match_redundant_explicit_literal_patterns(
value: Int, pair: Tuple[Int, String]
):
match value:
# expected-warning @+1 {{'==' is redundant when matching a literal; remove it}}
case == 0:
pass
case _:
pass
match pair:
# expected-warning @+1 {{'==' is redundant when matching a literal; remove it}}
case (_, == "expected"):
pass
case _:
pass
def match_expression_patterns_require_explicit_equality(
value: Int, pair: Tuple[Int, Int]
):
match value:
# expected-error @+1 {{expression is not a valid match pattern; use '==' to compare against its value}}
case pair[0]:
pass
case _:
pass
match pair:
# expected-error @+1 {{expression is not a valid match pattern; use '==' to compare against its value}}
case (_, pair[1] + 1):
pass
case _:
pass
def match_list_requires_sized(value: Int):
match value:
# expected-error @+1 {{value of type 'Int' does not conform to 'Sized'}}
case [element]:
_ = element
case _:
pass
def deprecated_dunder_match(value: Int):
# expected-warning @+1 {{'__match' is deprecated; use 'match'}}
__match value:
case _:
pass
@@ -0,0 +1,49 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
# Test that control flow statements at module/file scope emit errors instead
# of being silently accepted.
# RUN: %parse-mojo-isolated -verify-diagnostics %s
##===----------------------------------------------------------------------===##
# Control flow statements at module scope
##===----------------------------------------------------------------------===##
# expected-error @below {{'if' must be contained in a function}}
if True:
pass
# expected-error @below {{'for' must be contained in a function}}
for i in range(10):
pass
# expected-error @below {{'while' must be contained in a function}}
while True:
pass
# expected-error @below {{'with' must be contained in a function}}
with foo:
pass
##===----------------------------------------------------------------------===##
# Comptime control flow statements at module scope
##===----------------------------------------------------------------------===##
# expected-error @below {{'comptime if' must be contained in a function}}
comptime if True:
pass
# expected-error @below {{'comptime for' must be contained in a function}}
comptime for i in range(10):
pass
@@ -0,0 +1,25 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
# Test that 'try' statement at module scope emits an error.
# This is in a separate file because after 'try' is rejected, the 'except'
# keyword becomes an invalid token at module scope, causing a cascading error.
# RUN: %parse-mojo-isolated -verify-diagnostics %s
# expected-error @below {{'try' must be contained in a function}}
try:
pass
# expected-error @below {{unexpected token in expression}}
except:
pass
@@ -0,0 +1,244 @@
# ===----------------------------------------------------------------------=== #
# 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 -verify-diagnostics | FileCheck %s
##===----------------------------------------------------------------------===##
# Raise and Try
##===----------------------------------------------------------------------===##
# CHECK-LABEL: lit.fn @"simpleTryExcept
def simpleTryExcept():
var a: Int
# CHECK: lit.try
try:
# CHECK: lit.ref.store
a = 0
# CHECK-NEXT: lit.try.yield
# CHECK-NEXT: except
except:
# CHECK-NEXT: lit.try.yield
pass
# CHECK-NEXT: else
# CHECK-NEXT: lit.try.yield
# CHECK: lit.end_fn
# CHECK-LABEL: lit.fn @"tryExceptElse
def tryExceptElse():
var a: Int
# CHECK: lit.try
try:
pass
except:
pass
# CHECK: else
else:
# CHECK: lit.ref.store
a = 0
# CHECK-NEXT: lit.try.yield
def eatError(err: Error):
pass
# CHECK-LABEL: lit.fn @"tryExceptArgDef
def tryExceptArgDef():
try:
pass
# CHECK: } except {
except err:
# CHECK-NEXT: [[ERR:%.*]] = lit.ref.immut %err
# CHECK-NEXT: eatError{{.*}}([[ERR]])
eatError(err)
# CHECK-LABEL: lit.fn @"tryFinally
def tryFinally():
# CHECK: lit.try
try:
# CHECK-NEXT: lit.try.yield
pass
# CHECK-NEXT: except
# CHECK-NEXT: unreachable
# CHECK: finally
finally:
# CHECK: lit.return
return
# CHECK: lit.try %__try_error___0
try:
# CHECK: lit.try
try:
# CHECK-NEXT: lit.try.yield
pass
# CHECK-NEXT: except
# CHECK-NEXT: lit.call {{.*}}Error::@"__init__{{.*}}"{{.*}}(%__try_error___1, %__try_error___0){{.*}}*, "move"
# CHECK-NEXT: lit.raise
finally:
pass
except:
pass
# CHECK-LABEL: lit.fn @"tryExceptInTryFinally
def tryExceptInTryFinally():
# CHECK: lit.try %__try_error__
try:
# CHECK: lit.try %__try_error___0
try:
# CHECK-NEXT: lit.try.yield
pass
# CHECK-NEXT: } except {
# CHECK-NEXT: lit.try.yield
# CHECK-NEXT: } else {
# CHECK-NEXT: lit.try.yield
# CHECK-NEXT: } finally {
# CHECK-NEXT: lit.try.yield
# CHECK-NEXT: }
except:
pass
# CHECK-NEXT: lit.try.yield
# CHECK-NEXT: } except {
# CHECK-NEXT: hlcf.unreachable
# CHECK-NEXT: } else {
# CHECK-NEXT: lit.try.yield
# CHECK-NEXT: } finally {
# CHECK-NEXT: lit.try.yield
# CHECK-NEXT: }
finally:
pass
def maybeRaises() raises -> Int:
return 0
# CHECK-LABEL: lit.fn @"propagateErrorInDef
def propagateErrorInDef() raises:
# CHECK: %a = lit.var.decl "a"
# CHECK: lit.call {{.*}}maybeRaises{{.*}}(%__error__, %a)
var a = maybeRaises()
# CHECK-LABEL: lit.fn @"propagateErrorInRaisingFn
def propagateErrorInRaisingFn() raises:
# CHECK: %a = lit.var.decl {{.*}} : !lit.ref<:meta<!Int> #alias_Int,
var a: Int
# CHECK: lit.call {{.*}}maybeRaises{{.*}}(%__error__, %a)
a = maybeRaises()
# CHECK-LABEL: lit.fn @"propagateErrorInTry
def propagateErrorInTry():
var a: Int
# CHECK: lit.try
try:
# CHECK-NEXT: lit.call {{.*}}maybeRaises{{.*}}(%__try_error__, %a)
a = maybeRaises()
# CHECK-NEXT: lit.try.yield
except:
pass
# CHECK-LABEL: lit.fn @"raiseError
def raiseErrorInDef() raises:
# CHECK: lit.call {{.*}}@Error::@"__init__{{.*}}(%__error__)
# CHECK-NEXT: lit.raise
raise Error()
# CHECK-LABEL: lit.fn @"raiseErrorInIf
def raiseErrorInIf(cond: Bool) raises:
# CHECK: hlcf.if
if cond:
# CHECK: lit.call {{.*}}@Error::@"__init__{{.*}}(%__error__)
# CHECK-NEXT: lit.raise
raise Error()
# CHECK-LABEL: lit.fn @"raiseErrorInTry
def raiseErrorInTry():
# CHECK: lit.try %__try_error__
try:
# CHECK-NEXT: lit.call {{.*}}@Error::@"__init__{{.*}}(%__try_error__)
# CHECK-NEXT: lit.raise
raise Error()
except:
pass
# CHECK-LABEL: lit.fn @"rethrowsToRethrow
def rethrowsToRethrow():
# CHECK: lit.try [[TRY_ERROR1:%.*]] :
try:
# CHECK: lit.try [[TRY_ERROR2:%.*]] :
try:
# CHECK: lit.call {{.*}}maybeRaises{{.*}}([[TRY_ERROR2]], %__call_result_tmp__
maybeRaises() # expected-warning {{'Int' value is unused; assign to '_' to discard the result}}
# CHECK: } except {
except:
# CHECK-NEXT: lit.call {{.*}}Error::@"__init__{{.*}}"{{.*}}([[TRY_ERROR2]], [[TRY_ERROR1]]){{.*}}*, "move"
# CHECK-NEXT: lit.raise
raise
# CHECK: }
# CHECK: } except {
except:
# CHECK: lit.return %none
return
struct S(ImplicitlyCopyable, Movable):
var v: Int
@implicit
def __init__(out self, x: Int):
self.v = x
def __init__(out self) raises:
self.v = 1
def fail() raises -> S:
return 0
# CHECK-LABEL: lit.fn @"call_raising
def call_raising():
# CHECK: lit.try %e
try:
# CHECK: [[ERR:%.*]] = lit.call {{.*}}::@"fail{{.*}}(%e, %x)
var x = fail()
# CHECK: %y = lit.var.decl "y"
# CHECK-NEXT: lit.call {{.*}}__init__{{.*}}(%e, %y)
var y = S()
# CHECK-NEXT: lit.try.yield
except e:
pass
def fail_raises() raises -> S:
return fail()
def fail_register() raises -> Int:
return 0
# CHECK-LABEL: lit.fn @"fail_register_raises
def fail_register_raises() raises -> Int:
# CHECK-NEXT: call {{.*}}fail_register{{.*}}(%__error__, %__result__)
# CHECK-NEXT: [[FALSE:%.*]] = kgen.param.constant: scalar<bool> = <false>
# CHECK-NEXT: lit.return [[FALSE]]
return fail_register()
@@ -0,0 +1,88 @@
# ===----------------------------------------------------------------------=== #
# 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 -verify-diagnostics %s
##===----------------------------------------------------------------------===##
# Raise
##===----------------------------------------------------------------------===##
def raisingFunction() raises:
pass
# expected-note @below {{or mark surrounding function as 'raises'}}
def callRaisingFunction():
# expected-error @below {{cannot call function that may raise in a context that cannot raise}}
# expected-note @below {{try surrounding the call in a 'try' block}}
raisingFunction()
def cannotReRaise() raises:
# expected-error @below {{'raise' must live within an 'except' block or a function marked 'raises'}}
raise
def cannotRaise(err: Error):
# expected-error @below {{'raise' requires a surrounding 'try' block or the enclosing function to declare 'raises'}}
raise err
# Issue #12358
def raise_bad_type() raises:
raise 42 # expected-error {{cannot implicitly convert 'IntLiteral[42]' value to 'Error'}}
def raises_arg(x: String) raises Pointer[String, origin_of(x)]:
pass
struct OriginHolder(Movable):
var str: String
def __init__(out self):
self.str = String()
# MOCO-3000
def origin_scope_example():
try:
var key = 42 # expected-note {{origin declared here}}
# expected-error @+1 {{inferred error type 'Pointer[Int, origin_of(key)]' captures origin 'origin_of(key)' from within try body; it is not in scope in except body}}
raise Pointer(to=key)
except e:
_ = e[] # isn't valid.
try:
var str = String() # expected-note {{origin declared here}}
# expected-error @+1 {{inferred error type 'Pointer[String, origin_of(str)]' captures origin 'origin_of(str)' from within try body; it is not in scope in except body}}
raises_arg(str)
except e2:
_ = e2[] # isn't valid.
try:
# expected-error @below {{inferred error type 'Pointer[String, origin_of(__call_result_tmp__)]' captures origin of temporary from within try body; it is not in scope in except body}}
# expected-note @below {{origin declared here}}
raises_arg(String())
except e3:
_ = e3[] # isn't valid.
# An origin that refines one declared in the try body escapes just as the
# one it refines does, so what the error type captures is its base.
try:
var holder = OriginHolder() # expected-note {{origin declared here}}
# expected-error @+1 {{inferred error type 'Pointer[String, origin_of(holder.str)]' captures origin 'origin_of(holder)' from within try body; it is not in scope in except body}}
raise Pointer(to=holder.str)
except e4:
_ = e4[] # isn't valid.
@@ -0,0 +1,133 @@
# ===----------------------------------------------------------------------=== #
# 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 that control flow statements in struct/trait/extension bodies emit
# errors instead of crashing the compiler (MOCO-3870).
# RUN: %parse-mojo-isolated -verify-diagnostics %s
##===----------------------------------------------------------------------===##
# Control flow statements in struct body
##===----------------------------------------------------------------------===##
struct StructWithIf(Movable where False):
var x: Int
# expected-error @below {{'if' must be contained in a function}}
if True:
pass
struct StructWithFor(Movable where False):
var x: Int
# expected-error @below {{'for' must be contained in a function}}
for i in range(10):
pass
struct StructWithWhile(Movable where False):
var x: Int
# expected-error @below {{'while' must be contained in a function}}
while True:
pass
struct StructWithComptimeIf(Movable where False):
var x: Int
# expected-error @below {{'comptime if' must be contained in a function}}
comptime if True:
pass
struct StructWithComptimeFor(Movable where False):
var x: Int
# expected-error @below {{'comptime for' must be contained in a function}}
comptime for i in range(10):
pass
struct StructWithWith(Movable where False):
var x: Int
# expected-error @below {{'with' must be contained in a function}}
with foo:
pass
##===----------------------------------------------------------------------===##
# Control flow statements in trait body
##===----------------------------------------------------------------------===##
trait TraitWithIf:
# expected-error @below {{'if' must be contained in a function}}
if True:
pass
trait TraitWithFor:
# expected-error @below {{'for' must be contained in a function}}
for i in range(10):
pass
trait TraitWithWhile:
# expected-error @below {{'while' must be contained in a function}}
while True:
pass
trait TraitWithWith:
# expected-error @below {{'with' must be contained in a function}}
with foo:
pass
##===----------------------------------------------------------------------===##
# Control flow statements in extension body
##===----------------------------------------------------------------------===##
struct ExtendedStruct(Movable where False):
var x: Int
__extension ExtendedStruct:
# expected-error @below {{'if' must be contained in a function}}
if True:
pass
struct ExtendedStruct2(Movable where False):
var x: Int
__extension ExtendedStruct2:
# expected-error @below {{'for' must be contained in a function}}
for i in range(10):
pass
struct ExtendedStruct3(Movable where False):
var x: Int
__extension ExtendedStruct3:
# expected-error @below {{'while' must be contained in a function}}
while True:
pass
struct ExtendedStruct4(Movable where False):
var x: Int
__extension ExtendedStruct4:
# expected-error @below {{'comptime if' must be contained in a function}}
comptime if True:
pass
struct ExtendedStruct5(Movable where False):
var x: Int
__extension ExtendedStruct5:
# expected-error @below {{'comptime for' must be contained in a function}}
comptime for i in range(10):
pass
struct ExtendedStruct6(Movable where False):
var x: Int
__extension ExtendedStruct6:
# expected-error @below {{'with' must be contained in a function}}
with foo:
pass
@@ -0,0 +1,58 @@
# ===----------------------------------------------------------------------=== #
# 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 that 'try' statement in type bodies emits an error.
# This is in a separate file because after 'try' is rejected, the 'except'
# keyword becomes an invalid token, causing a cascading error.
# RUN: %parse-mojo-isolated -verify-diagnostics %s
##===----------------------------------------------------------------------===##
# try in struct body
##===----------------------------------------------------------------------===##
struct StructWithTry(Movable where False):
var x: Int
# expected-error @below {{'try' must be contained in a function}}
try:
pass
# expected-error @below {{unexpected token in expression}}
except:
pass
##===----------------------------------------------------------------------===##
# try in trait body
##===----------------------------------------------------------------------===##
trait TraitWithTry:
# expected-error @below {{'try' must be contained in a function}}
try:
pass
# expected-error @below {{unexpected token in expression}}
except:
pass
##===----------------------------------------------------------------------===##
# try in extension body
##===----------------------------------------------------------------------===##
struct ExtendedStructWithTry(Movable where False):
var x: Int
__extension ExtendedStructWithTry:
# expected-error @below {{'try' must be contained in a function}}
try:
pass
# expected-error @below {{unexpected token in expression}}
except:
pass