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,55 @@
# ===----------------------------------------------------------------------=== #
# 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 -import-mojo -verify-diagnostics -split-input-file %s
# expected-error @below {{cannot unpack value of 'Tuple[Int, FloatDyn]' of 2 elements into 3 values}}
comptime a, (b, c, d) = (1, (2, 3.0))
# // -----
# expected-error @below {{invalid comptime declaration: expected an identifier or '_'}}
comptime t, True, c = 1, 2, 3
# // -----
struct A:
# expected-error @below {{'comptime' constants inside structs must be declared separately; break this into individual declarations}}
comptime a, b = 1, 2
# // -----
trait A:
# expected-error @below {{a trait's associated types must be declared separately; break this into individual declarations}}
comptime a, b = 1, 2
# // -----
# expected-note @below {{previous definition here}}
comptime a, b = 1, 2
# expected-error @below {{invalid redefinition of 'b'}}
comptime b, c = 2, 3
# // -----
def example[list: List[Int]]():
# expected-error @below {{cannot destructure into list patterns yet}}
comptime for [a, b] in list:
pass
@@ -0,0 +1,152 @@
# ===----------------------------------------------------------------------=== #
# 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 -split-input-file -verify-diagnostics %s -o /dev/null
# expected-error @below {{only traits may contain a comptime member without an initializer}}
comptime K: Int
trait MyTrait: # expected-note {{trait 'MyTrait' declared here}}
# expected-note @below {{required member 'N' is not specified}}
# expected-note @below {{comptime member 'N' type 'Bool' does not conform to trait's required type 'Int'}}
comptime N: Int
# expected-error @below {{'StructConformingExplicitlyWithNoMatchingAlias' does not implement all requirements for 'MyTrait'}}
struct StructConformingExplicitlyWithNoMatchingAlias(MyTrait, Movable where False):
pass
# expected-error @below {{'StructConformingExplicitlyWithMismatchedAlias' does not implement all requirements for 'MyTrait'}}
struct StructConformingExplicitlyWithMismatchedAlias(MyTrait, Movable where False):
comptime N: Bool = Bool()
# expected-error @below {{'StructConformingExplicitlyWithMemberSameName' does not implement all requirements for 'MyTrait'}}
struct StructConformingExplicitlyWithMemberSameName(MyTrait, Movable where False):
var N: Int
@fieldwise_init
struct StructWithNoMatchingAlias(Movable where False):
pass
@fieldwise_init
struct StructWithMismatchedAlias(Movable where False):
comptime N: Bool = Bool()
struct StructWithUninitializedAlias(Movable where False):
# expected-error @below {{only traits may contain a comptime member without an initializer}}
comptime N: Bool
struct StructWithTypelessUninitializedAlias(Movable where False):
# This makes sure we print out this error, rather than the also-relevant "alias without initial value must have a type" error
# expected-error @below {{expected '=' after comptime declaration}}
comptime N
# expected-note @below {{function declared here}}
def funcForMyTrait[T: MyTrait](t: T) -> Int:
comptime X = T.N
return X
def testError1():
# TODO(MOCO-1152): Add more detailed errors for this
# expected-error @below {{invalid call to 'funcForMyTrait': value passed to 't' cannot be converted from 'StructWithNoMatchingAlias' to 'T', argument type 'StructWithNoMatchingAlias' does not conform to trait 'MyTrait'}}
var whatev: Int = funcForMyTrait(StructWithNoMatchingAlias())
def testError2():
# TODO(MOCO-1152): Add more detailed errors for this
# expected-error @below {{invalid call to 'funcForMyTrait': value passed to 't' cannot be converted from 'StructWithMismatchedAlias' to 'T', argument type 'StructWithMismatchedAlias' does not conform to trait 'MyTrait'}}
var whatev: Int = funcForMyTrait(StructWithMismatchedAlias())
# // -----
struct TensorIndex[rank: Int](Movable where False):
pass
trait Stencil:
comptime rank: Int
# // -----
# Tests that we get a nice error when an override alias has an incompatible
# type.
struct ZInt:
pass
struct ZBool:
pass
trait TraitWithTypeAlias:
# expected-note @below {{the other trait's member defined here}}
comptime T: ZBool
trait TraitWithSameTypeAlias(TraitWithTypeAlias):
# expected-error @below {{invalid redefinition of 'T': cannot convert 'ZInt' to the other trait's member's type 'ZBool'}}
comptime T: ZInt
# // -----
# Makes sure that we don't crash if there are multiple overrides.
struct ZInt:
pass
struct ZBool:
pass
struct ZFloat(Movable where False):
pass
trait SuperTrait:
comptime T: ZFloat
trait TraitWithTooManyAliases(SuperTrait):
# expected-note @below {{previous definition here}}
comptime T: ZBool
# expected-error @below {{invalid redefinition of 'T'}}
comptime T: ZInt
# // -----
trait TraitWithComptime:
# expected-note @+1 {{conflicting comptime alias declared here}}
comptime MyType = Int
trait ChildOverridesComptimeWithFn(TraitWithComptime):
# expected-error @+1 {{invalid redefinition of 'MyType'}}
def MyType(self):
pass
@@ -0,0 +1,233 @@
# ===----------------------------------------------------------------------=== #
# 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
##===----------------------------------------------------------------------===##
# declarations
##===----------------------------------------------------------------------===##
# expected-error @below {{use of unknown declaration 'y'}}
comptime unknownDecl[x: Int] = y
# expected-error @below {{cannot implicitly convert 'Int' value to 'String'}}
comptime wrongType[x: Int]: String = x
comptime myIntAdd[x: Int, y: Int] = x + y
# expected-error @+2 {{'where' clauses inside parameter lists are no longer supported}}
# expected-note @+1 {{use a trailing 'where' clause after the signature instead}}
comptime inlineWhereIsError[x: Int where x > 0] = x
# expected-error @below {{cannot implicitly convert 'SIMD[.int, x]' value to 'SIMD[.int, (x * Int(20))]'}}
comptime ComptimeWithParametricType2[x: Int]: SIMD[.int, x*20] = SIMD[.int, x]()
def implicit_generator_constraint_drop_error[cond: Bool]():
comptime constrained[x: Int]: AnyType where cond = Int
# expected-error @below {{cannot implicitly convert '__generator_type[x: Int] AnyType where cond' value to '__generator_type[x: Int] AnyType' in comptime initializer}}
comptime dropped: __generator_type[x: Int] AnyType = constrained
def implicit_generator_constraint_drop_env_mismatch_error[
cond: Bool, other: Bool
]() where other:
comptime constrained[x: Int]: AnyType where cond = Int
# expected-error @below {{cannot implicitly convert '__generator_type[x: Int] AnyType where cond' value to '__generator_type[x: Int] AnyType' in comptime initializer}}
comptime dropped: __generator_type[x: Int] AnyType = constrained
# Discharging a generator body constraint depends on the assumptions in scope,
# so its convertibility result must never be cached: the convertibility cache is
# keyed only on the (value, required) type pair. The two scopes above failed to
# discharge `where cond` for the `[x: Int] AnyType` generator/body pair; this
# scope proves `cond` and must still succeed for the *same* type pair. If a
# scope-dependent result were cached, the failures above would poison this query
# and produce a spurious "cannot implicitly convert" diagnostic here.
def implicit_generator_constraint_drop_cross_scope[cond: Bool]() where cond:
comptime constrained[x: Int]: AnyType where cond = Int
comptime dropped: __generator_type[x: Int] AnyType = constrained
# A target that keeps `condB` is reachable: the source's constraints are all
# dropped and the value is rebound to the target type, so nothing retains a
# mismatched source location. `condA` is provable in this scope, and `condB` is
# assumed because the target promises it.
def implicit_generator_constraint_drop_partial[
condA: Bool, condB: Bool
]() where condA where condB:
comptime keepsB[x: Int]: AnyType where condB = Int
comptime bothConstraints[x: Int]: AnyType where condA where condB = Int
comptime r: type_of(keepsB) = bothConstraints
# Adding a body constraint the source lacks is fine: constraints are
# contravariant, so a source that demands less satisfies a target that promises
# more.
def implicit_generator_constraint_add[condA: Bool, condB: Bool]() where condA where condB:
comptime onlyA[x: Int]: AnyType where condA = Int
comptime bothConstraints[x: Int]: AnyType where condA where condB = Int
comptime r: type_of(bothConstraints) = onlyA
# The target's constraints are only assumptions, not a licence to ignore the
# source's. `condB` is unprovable here, so the source's `where condA, condB`
# cannot be discharged against a target that only promises `condA`.
def implicit_generator_constraint_unprovable_error[
condA: Bool, condB: Bool
]() where condA:
comptime onlyA[x: Int]: AnyType where condA = Int
comptime bothConstraints[x: Int]: AnyType where condA where condB = Int
# expected-error @below {{cannot implicitly convert '__generator_type[x: Int] AnyType where condA, condB' value to '__generator_type[x: Int] AnyType where condA' in comptime initializer}}
comptime r: type_of(onlyA) = bothConstraints
comptime myCurriedIntAdd[x: Int] = myIntAdd[x, ...]
# expected-error @below {{unexpected keyword parameter 'y'}}
comptime myCurriedIntAdd2 = myCurriedIntAdd[y=2]
comptime myRenamedCurriedIntAdd[a: Int] = myCurriedIntAdd[a]
# expected-error @below {{unexpected keyword parameter 'x'}}
comptime myRenamedCurriedIntAdd2 = myRenamedCurriedIntAdd[x=2]
# expected-error @below {{'Int' is not subscriptable}}
comptime mySix = myCurriedIntAdd[2][4][6]
comptime myIntAddTooManyParams = myIntAdd[1, 2,
3] # expected-error {{unexpected parameter}}
# COM: A type with dependent parameters.
struct Dep[T: AnyType, v: T](Movable where False):
pass
comptime MyDep[T: AnyType, v: T] = Dep[T, v]
# expected-error @below {{'T' refers to an unbound parameter in 'MyDep'}}
# expected-note @below {{'MyDep' is aka 'comptime[T: AnyType, v: T] Dep[T, v]'}}
comptime MyDepDotT = MyDep.T
# expected-error @below {{'Dep[_, _]' value has no attribute 'hello'}}
comptime MyDepGetAlias0 = MyDep.hello
# expected-error @below {{'Dep[Int, _]' value has no attribute 'hello'}}
comptime MyDepGetAlias1 = MyDep[Int].hello
# expected-error @below {{'Dep[Int, Int(2)]' value has no attribute 'hello'}}
comptime MyDepGetAlias2 = MyDep[Int, 2].hello
# COM: Using a generator as a struct field type should be rejected (MOCO-3514).
struct FieldWithUnboundAlias(Movable where False):
# expected-error @below {{'MyDep' is not a concrete type, use '[]' to bind missing parameters}}
# expected-note @below {{'MyDep' is aka 'comptime[T: AnyType, v: T] Dep[T, v]'}}
var f: MyDep
def test_variable_type_parameterization():
# Store an unparameterized struct type in a variable...
# expected-error @below {{dynamic type values not permitted yet; try creating a 'comptime' instead of a 'var'}}
var struct_type = Dep
# .. and try to parameterize it.
# expected-error @below {{types are not subscriptable}}
var instance: struct_type[Int]
##===----------------------------------------------------------------------===##
# Trailing 'where' constraints are enforced when the alias's parameters are
# inferred during auto-parameterization, not just for explicit bindings
# (MOCO-4081). This covers every form that auto-parameterizes the alias
# generator: argument types, value-parameter types, and variadic element types.
##===----------------------------------------------------------------------===##
@fieldwise_init
struct Tag[n: Int](Copyable, Movable):
pass
# A distinct alias is used per form so each violated call's note points at its
# own 'where' clause (identical notes at one location are coalesced by the
# diagnostic verifier).
# Alias used as a function argument type.
# expected-note @+1 {{constraint declared here evaluated to False, expected '(n > Int(0))'}}
comptime PositiveArg[n: Int, //] where n > 0 = Tag[n]
# expected-note @+1 {{function declared here}}
def take_arg(p: PositiveArg):
pass
# Alias used as a value-parameter type.
# expected-note @+1 {{constraint declared here evaluated to False, expected '(n > Int(0))'}}
comptime PositiveParam[n: Int, //] where n > 0 = Tag[n]
# expected-note @+1 {{function declared here}}
def take_param[p: PositiveParam]():
pass
# Alias used as a variadic argument element type.
# expected-note @+1 {{constraint declared here evaluated to False, expected '(n > Int(0))'}}
comptime PositiveVar[n: Int, //] where n > 0 = Tag[n]
# expected-note @+1 {{function declared here}}
def take_variadic(*p: PositiveVar):
pass
def use_ok():
# Inferred bindings that satisfy the constraint are accepted in every form.
take_arg(Tag[1]())
take_param[Tag[1]()]()
take_variadic(Tag[1](), Tag[1]())
def use_arg_bad():
# expected-error @+1 {{invalid call to 'take_arg': violated constraint}}
take_arg(Tag[-1]())
def use_param_bad():
# expected-error @+1 {{invalid call to 'take_param': violated constraint}}
take_param[Tag[-1]()]()
def use_variadic_bad():
# expected-error @+1 {{invalid call to 'take_variadic': violated constraint}}
take_variadic(Tag[-1]())
##===----------------------------------------------------------------------===##
# Handle type alias with extra constraints
##===----------------------------------------------------------------------===##
struct Iter[Cond: Bool](Movable where False):
# expected-note @+1 {{function declared here}}
def __init__(out self: Iter[False]):
pass
struct Collection[Cond: Bool]:
# expected-note @+1 {{constraint declared here evaluated to False, expected 'Cond'}}
comptime Alias[Cond: Bool]: AnyType where Cond = Iter[Cond]
def iter(self) where Self.Cond:
# Inferring to `Iter[False]` violates the constraint imposed on `Alias`
#
# expected-error @+1 {{invalid initialization: violated constraint}}
_ = Self.Alias()
@@ -0,0 +1,129 @@
# ===----------------------------------------------------------------------=== #
# 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
# Test error cases for @align decorator.
# expected-error @+1 {{@align value must be a positive power of 2}}
@align(0)
struct ZeroAlign(Movable where False):
var x: Int
# -1 is parsed as unary negation, not an integer literal
# expected-error @+1 {{@align value must be a positive power of 2}}
@align(-1)
struct NegativeAlign(Movable where False):
var x: Int
# expected-error @+1 {{@align value must be a positive power of 2}}
@align(3)
struct NotPowerOfTwo1(Movable where False):
var x: Int
# expected-error @+1 {{@align value must be a positive power of 2}}
@align(5)
struct NotPowerOfTwo2(Movable where False):
var x: Int
# expected-error @+1 {{@align value must be a positive power of 2}}
@align(6)
struct NotPowerOfTwo3(Movable where False):
var x: Int
# expected-error @+1 {{@align value must be a positive power of 2}}
@align(7)
struct NotPowerOfTwo4(Movable where False):
var x: Int
# expected-error @+1 {{@align value must be a positive power of 2}}
@align(100)
struct NotPowerOfTwo5(Movable where False):
var x: Int
# expected-error @+1 {{@align requires exactly one argument}}
@align
struct MissingArgument(Movable where False):
var x: Int
# expected-error @+1 {{@align requires exactly one argument}}
@align()
struct EmptyArguments(Movable where False):
var x: Int
# expected-error @+1 {{@align requires exactly one argument}}
@align(64, 128)
struct TooManyArguments(Movable where False):
var x: Int
# expected-error @+1 {{'StringLiteral["64"]' does not implement the '__mlir_index__' method}}
@align("64")
struct StringArgument(Movable where False):
var x: Int
# expected-error @+1 {{@align value exceeds maximum alignment (2^29)}}
@align(1073741824) # 2^30, exceeds maximum
struct ExcessiveAlignment(Movable where False):
var x: Int
# expected-error @+1 {{@align value exceeds maximum alignment (2^29)}}
@align(4294967296) # 2^32, exceeds maximum
struct ExcessiveAlignment2(Movable where False):
var x: Int
# @align(1) is allowed without warning - useful for parametric alignment fallback
@align(1)
struct AlignOne(Movable where False):
var x: Int
# Test referencing a non-existent parameter
# expected-error @+1 {{use of unknown declaration 'nonexistent'}}
@align(nonexistent)
struct NonExistentParam(Movable where False):
var x: Int
# Test referencing a non-existent parameter
# expected-error @+1 {{use of unknown declaration 'missing'}}
@align(missing)
struct NonExistentParamExpr(Movable where False):
var x: Int
# Test using a non-Int typed parameter
# expected-error @+1 {{'String' does not implement the '__mlir_index__' method}}
@align(s)
struct WrongTypeParam[s: String](Movable where False):
var x: Int
# Test using a Self. parameter
# expected-error @+1 {{'Self' type is not available in this context}}
@align(Self.x)
struct SelfParam[x: Int](Movable where False):
pass
@@ -0,0 +1,464 @@
# ===----------------------------------------------------------------------=== #
# 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
##===----------------------------------------------------------------------===##
# Auto-Predication During Signature Emission
#
# When a parametric struct appears in a function or struct signature
# (parameter declaration, function argument, return type, or thrown type),
# binding the struct's parameters can produce unprovable body constraints:
# the trailing `where` clauses are parsed AFTER the signature, so their
# assumptions aren't yet in scope at the binding site.
#
# The auto-predication feature collects these unprovable body constraints into a
# deferral context during signature emission and ensures that each one is
# implied by any body constraints on the signature.
#
# Wiring covered by these tests:
# - Function parameter declaration types (`TypeCheckedParamList::create`)
# - Function argument types (`typeCheckOneArgument`)
# - Function return types (`typeCheckResult`)
# - Function `raises T` thrown types (`typeCheckResult` errorType branch)
# - Struct parameter declaration types (`TypeCheckedParamList::create`)
#
# Per-parameter `where` constraints are intentionally NOT deferred (they
# would change candidate viability during overload resolution); the cases
# below only cover body (trailing) constraints.
##===----------------------------------------------------------------------===##
##===----------------------------------------------------------------------===##
# Discharged via trailing `where` on a function
##===----------------------------------------------------------------------===##
# A parametric binding whose body constraint is unprovable at the binding
# site is deferred and successfully discharged once the trailing `where`
# clause has been folded into the decl scope's known assumptions. The
# cases below should type-check without diagnostics.
struct PositiveOnly[N: Int] (Movable where False) where N > 0:
pass
struct OnlyIntable[T: AnyType] (Movable where False) where conforms_to(T, Intable):
pass
# Parameter declaration position.
def discharged_from_param_int[K: Int, X: PositiveOnly[K]]() where K > 0:
pass
def discharged_from_param_trait[T: AnyType, X: OnlyIntable[T]]()
where conforms_to(T, Intable):
pass
# Argument type position.
def discharged_from_arg_int[K: Int](x: PositiveOnly[K]) where K > 0:
pass
def discharged_from_arg_trait[T: AnyType](x: OnlyIntable[T])
where conforms_to(T, Intable):
pass
# Return type position.
def discharged_from_ret[K: Int]() -> PositiveOnly[K] where K > 0:
pass
# Thrown type position (`raises T`).
def discharged_from_throws[K: Int]() raises PositiveOnly[K] where K > 0:
pass
##===----------------------------------------------------------------------===##
# Discharged via trailing `where` on a struct
##===----------------------------------------------------------------------===##
# Structs go through the same flow as functions, so deferral and discharge apply
# identically to struct parameter declaration positions.
struct DischargedStruct[K: Int, X: PositiveOnly[K]] (Movable where False) where K > 0:
pass
struct DischargedStructTrait[T: AnyType, X: OnlyIntable[T]]
(Movable where False) where conforms_to(T, Intable):
pass
##===----------------------------------------------------------------------===##
# Multiple deferrals — all discharged
##===----------------------------------------------------------------------===##
# When a signature introduces multiple deferred body constraints, the
# discharge loop iterates over each independently and discharges those
# implied by the trailing `where`.
def all_discharged[A: Int, B: Int,
X: PositiveOnly[A], Y: PositiveOnly[B]]()
where A > 0 where B > 0:
pass
struct AllDischargedStruct[A: Int, B: Int,
X: PositiveOnly[A], Y: PositiveOnly[B]]
(Movable where False) where A > 0 where B > 0:
pass
##===----------------------------------------------------------------------===##
# Unprovable in function parameter declaration position
##===----------------------------------------------------------------------===##
struct PosForParam[N: Int]
# expected-note @below {{constraint declared here needs evidence for '(K > Int(0))'}}
(Movable where False) where N > 0:
pass
# expected-note @below {{add a trailing 'where' clause that requires '(K > Int(0))'}}
def undischarged_param[K: Int,
# expected-error @below {{invalid bindings in signature: lacking evidence to prove correctness}}
X: PosForParam[K]]():
pass
##===----------------------------------------------------------------------===##
# Unprovable in function argument position
##===----------------------------------------------------------------------===##
struct PosForArg[N: Int]
# expected-note @below {{constraint declared here needs evidence for '(K > Int(0))'}}
(Movable where False) where N > 0:
pass
# expected-note @below {{add a trailing 'where' clause that requires '(K > Int(0))'}}
def undischarged_arg[K: Int](
# expected-error @below {{invalid bindings in signature: lacking evidence to prove correctness}}
x: PosForArg[K]):
pass
##===----------------------------------------------------------------------===##
# Unprovable in function return type position
##===----------------------------------------------------------------------===##
struct PosForRet[N: Int]
# expected-note @below {{constraint declared here needs evidence for '(K > Int(0))'}}
(Movable where False) where N > 0:
pass
# expected-error @below {{invalid bindings in signature: lacking evidence to prove correctness}}
# expected-note @below {{add a trailing 'where' clause that requires '(K > Int(0))'}}
def undischarged_ret[K: Int]() -> PosForRet[K]:
pass
##===----------------------------------------------------------------------===##
# Unprovable in function `raises T` thrown type position
##===----------------------------------------------------------------------===##
struct PosForThrows[N: Int]
# expected-note @below {{constraint declared here needs evidence for '(K > Int(0))'}}
(Movable where False) where N > 0:
pass
# expected-error @below {{invalid bindings in signature: lacking evidence to prove correctness}}
# expected-note @below {{add a trailing 'where' clause that requires '(K > Int(0))'}}
def undischarged_throws[K: Int]() raises PosForThrows[K]:
pass
##===----------------------------------------------------------------------===##
# Unprovable in struct parameter declaration position
##===----------------------------------------------------------------------===##
struct PosForStruct[N: Int]
# expected-note @below {{constraint declared here needs evidence for '(K > Int(0))'}}
(Movable where False) where N > 0:
pass
# expected-note @below {{add a trailing 'where' clause that requires '(K > Int(0))'}}
struct UndischargedStruct[K: Int,
# expected-error @below {{invalid bindings in signature: lacking evidence to prove correctness}}
X: PosForStruct[K]](Movable where False):
pass
##===----------------------------------------------------------------------===##
# Multiple deferrals — partial discharge
##===----------------------------------------------------------------------===##
# Each deferred constraint is re-checked independently; the discharge loop
# reports an error per still-unprovable constraint while silently
# discharging the rest. Here only `A > 0` is in the where clause, so the
# `B > 0` constraint from `PosForPartial[B]` remains unprovable.
struct PosForPartial[N: Int]
# expected-note @below {{constraint declared here needs evidence for '(B > Int(0))'}}
(Movable where False) where N > 0:
pass
# expected-note @below {{add a trailing 'where' clause that requires '(B > Int(0))'}}
def partial_discharge[A: Int, B: Int, X: PosForPartial[A],
# expected-error @below {{invalid bindings in signature: lacking evidence to prove correctness}}
Y: PosForPartial[B]]() where A > 0:
pass
##===----------------------------------------------------------------------===##
# Unprovable trait conformance — function parameter declaration
##===----------------------------------------------------------------------===##
struct IntableForParam[T: AnyType]
# expected-note @below {{constraint declared here needs evidence for 'conforms_to(T, Intable)'}}
(Movable where False) where conforms_to(T, Intable):
pass
# expected-note @below {{add a trailing 'where' clause that requires 'conforms_to(T, Intable)'}}
def undischarged_trait_param[T: AnyType,
# expected-error @below {{invalid bindings in signature: lacking evidence to prove correctness}}
X: IntableForParam[T]]():
pass
##===----------------------------------------------------------------------===##
# Unprovable trait conformance — function argument
##===----------------------------------------------------------------------===##
struct IntableForArg[T: AnyType]
# expected-note @below {{constraint declared here needs evidence for 'conforms_to(T, Intable)'}}
(Movable where False) where conforms_to(T, Intable):
pass
# expected-note @below {{add a trailing 'where' clause that requires 'conforms_to(T, Intable)'}}
def undischarged_trait_arg[T: AnyType](
# expected-error @below {{invalid bindings in signature: lacking evidence to prove correctness}}
x: IntableForArg[T]):
pass
##===----------------------------------------------------------------------===##
# Multiple deferrals — none discharged
##===----------------------------------------------------------------------===##
# When no trailing `where` clause is present, every deferred body constraint
# remains unprovable and the discharge loop emits one error per constraint.
struct PosForNoneA[N: Int]
# expected-note @below {{constraint declared here needs evidence for '(A > Int(0))'}}
(Movable where False) where N > 0:
pass
struct PosForNoneB[N: Int]
# expected-note @below {{constraint declared here needs evidence for '(B > Int(0))'}}
(Movable where False) where N > 0:
pass
# expected-note @below {{add a trailing 'where' clause that requires '(A > Int(0))'}}
# expected-note @below {{add a trailing 'where' clause that requires '(B > Int(0))'}}
def all_undischarged[A: Int,
# expected-error @below {{invalid bindings in signature: lacking evidence to prove correctness}}
X: PosForNoneA[A],
B: Int,
# expected-error @below {{invalid bindings in signature: lacking evidence to prove correctness}}
Y: PosForNoneB[B]]():
pass
##===----------------------------------------------------------------------===##
# Multi-candidate deferral rejection
##===----------------------------------------------------------------------===##
# When the deferral sink is installed but overload resolution leaves more
# than one body-constraint-inconclusive candidate, deferral is rejected
# (we cannot commit to a single candidate). The normal inconclusiveness
# error fires, plus an extra note explaining why deferral did not apply.
# expected-note @below {{cannot prove constraint for candidate}}
def mc_target[K: Int](dummy: Int) -> Int
# expected-note @below {{constraint declared here}}
where K > 0:
return dummy
# expected-note @below {{cannot prove constraint for candidate}}
def mc_target[K: Int](dummy: Int) -> Int
# expected-note @below {{constraint declared here}}
where K < 100:
return dummy
struct MCReceiver[i: Int](Movable where False):
pass
def multi_cand_deferral_rejected[K: Int](
# expected-error @below {{ambiguous call to 'mc_target': lacking evidence to select candidate}}
# expected-note @below {{provide evidence for or against the constraints here to aid in candidate selection}}
# expected-note @below {{body constraints cannot be deferred because more than one candidate is inconclusive}}
x: MCReceiver[mc_target[K](0)]):
pass
##===----------------------------------------------------------------------===##
# Trait-bounded parameter slot conformance — discharged via trailing `where`
##===----------------------------------------------------------------------===##
# Distinct from the cases above: here the *slot itself* is trait-bounded
# (`T: Copyable`), so binding a value whose current bound is weaker (e.g. a
# `Movable` type parameter) fails the metatype conversion at the binding site
# rather than producing a nested body constraint. The conformance obligation is
# reified and deferred, then discharged by the trailing
# `where conforms_to(..., Copyable)`. These cases should type-check without
# diagnostics.
struct NeedsCopyable[T: Copyable](Movable where False):
pass
# Return type position.
def slot_discharged_ret[T: Movable]() -> NeedsCopyable[T]
where conforms_to(T, Copyable):
pass
# Argument type position.
def slot_discharged_arg[T: Movable](x: NeedsCopyable[T])
where conforms_to(T, Copyable):
pass
# Parameter declaration position.
def slot_discharged_param[T: Movable, X: NeedsCopyable[T]]()
where conforms_to(T, Copyable):
pass
# Thrown type position (`raises T`).
def slot_discharged_throws[T: Movable]() raises NeedsCopyable[T]
where conforms_to(T, Copyable):
pass
# Method form (the MOCO-4190 reproducer): `Self.T` from the parent struct.
struct SlotContainer[T: Movable](Movable where False):
def get(self) -> NeedsCopyable[Self.T] where conforms_to(Self.T, Copyable):
pass
# Struct parameter declaration position.
struct SlotDischargedStruct[T: Movable, X: NeedsCopyable[T]]
(Movable where False) where conforms_to(T, Copyable):
pass
##===----------------------------------------------------------------------===##
# Trait-bounded parameter slot conformance — undischarged
##===----------------------------------------------------------------------===##
# Without a trailing `where`, the deferred conformance obligation remains
# unprovable and the discharge loop reports it at the binding site, pointing the
# user at the `where` clause they should add.
# expected-error @below {{invalid bindings in signature: lacking evidence to prove correctness}}
# expected-note @below {{constraint declared here needs evidence for 'conforms_to(T, Copyable)'}}
# expected-note @below {{add a trailing 'where' clause that requires 'conforms_to(T, Copyable)'}}
def slot_undischarged_ret[T: Movable]() -> NeedsCopyable[T]:
pass
##===----------------------------------------------------------------------===##
# Trait-bounded parameter slot conformance — concrete receiver stays a hard error
##===----------------------------------------------------------------------===##
# A concrete type that does not conform to the slot's trait can never be rescued
# by a trailing `where`, so deferral must NOT apply: the precise binding-site
# diagnostic is preserved. This guards the type-parameter gate on deferral.
struct MoveOnly(Movable):
pass
# expected-note @below {{'NeedsCopyableConcrete' declared here}}
struct NeedsCopyableConcrete[T: Copyable](Movable where False):
pass
# expected-error @below {{'NeedsCopyableConcrete' parameter 'T' has 'Copyable' type, but value has type 'AnyStruct[MoveOnly]'}}
def concrete_non_copyable() -> NeedsCopyableConcrete[MoveOnly]:
pass
##===----------------------------------------------------------------------===##
# Trait-bounded slot conformance — compound (conditionally-conforming) receiver
##===----------------------------------------------------------------------===##
# The receiver need not be a bare type parameter. A compound parametric type
# with a *conditional* conformance (e.g. `CondCopyable[U]`, which is `Copyable`
# only when `U` is) reports `NeedsEvidence` rather than `No`, so it is also
# deferred. The obligation is folded before it is recorded, reducing the
# conditional conformance to its condition, so a trailing `where` discharges it
# whether it names the compound receiver or just the condition. Diagnostics
# report the reduced form, which is what a `where` clause has to state.
struct CondCopyable[T: Movable & Deinitable](
Copyable where conforms_to(T, Copyable), Movable
):
var value: Self.T
def __init__(out self, var value: Self.T):
self.value = value^
# Discharged: the trailing `where` names the compound receiver's conformance.
def cond_discharged[U: Movable & Deinitable]() -> NeedsCopyable[CondCopyable[U]]
where conforms_to(CondCopyable[U], Copyable):
pass
# Discharged: naming the condition works too, since the obligation reduces to it.
def cond_discharged_via_condition[U: Movable & Deinitable]() ->
NeedsCopyable[CondCopyable[U]] where conforms_to(U, Copyable):
pass
# Undischarged: no trailing `where`, so the deferred obligation stays unprovable
# and the discharge loop points at the `where` that would satisfy it.
# expected-error @below {{invalid bindings in signature: lacking evidence to prove correctness}}
# expected-note @below {{constraint declared here needs evidence for 'conforms_to(U, Copyable)'}}
# expected-note @below {{add a trailing 'where' clause that requires 'conforms_to(U, Copyable)'}}
def cond_undischarged[U: Movable & Deinitable]() -> NeedsCopyable[CondCopyable[U]]:
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.
# ===----------------------------------------------------------------------=== #
# RUN: %parse-mojo-isolated -verify-diagnostics -split-input-file %s
struct a(TrivialRegisterPassable):
@always_inline("builtin")
def b(c, d: a):
c & d
@always_inline("builtin")
def __rand__(c, e: a):
# expected-error @below {{'@always_inline("builtin")' does not support recursion}}
e & c
# // -----
struct S(TrivialRegisterPassable):
@always_inline("builtin")
def f(self, x: S):
# expected-error @below {{'@always_inline("builtin")' does not support recursion}}
self.f(x)
# // -----
struct S(TrivialRegisterPassable):
@always_inline("builtin")
def f(self, x: S):
self.g(x)
@always_inline("builtin")
def g(self, x: S):
# expected-error @below {{'@always_inline("builtin")' does not support recursion}}
self.f(x)
@@ -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 -I %S/inputs %s -split-input-file -verify-diagnostics
# Test suite for ambiguous import detection (MOCO-3264).
# Each section is an independent compilation unit.
#
# Input module structure: each test scenario uses a dedicated pair of input
# packages (e.g. struct_a/struct_b, fn_a/fn_b). This looks redundant — a
# single pair of packages with multiple differently-named exports and aliased
# imports (`from mod_a import StructFoo as Foo`) could in principle cover all
# cases. However, -verify-diagnostics checks @expected-note annotations in ALL
# SourceMgr buffers, including imported modules. Because different test sections
# trigger notes at different declaration sites within the same shared module,
# a shared module cannot satisfy all sections simultaneously without spurious
# "expected note not found" failures. Dedicated per-scenario packages avoid
# this constraint cleanly.
# ---------------------------------------------------------------------------
# Structs: importing two different structs with the same name produces an
# error at the second import statement, not at the use site.
from struct_a import Foo
# @expected-error @below {{import of 'Foo' is ambiguous}}
from struct_b import Foo
# After the import error the first struct is still usable.
def use_it[x: Foo]():
pass
# // -----
# ---------------------------------------------------------------------------
# Type aliases (comptime): same rule applies — ambiguous import detected at
# the second import statement.
from comptime_a import Foo
# @expected-error @below {{import of 'Foo' is ambiguous}}
from comptime_b import Foo
def use_alias[x: Foo]():
pass
# // -----
# ---------------------------------------------------------------------------
# Functions: an overload set resolves from a single origin; importing
# functions with the same name from different modules is not permitted.
from fn_a import Foo
# @expected-error @below {{import of 'Foo' is ambiguous}}
from fn_b import Foo
def call_it():
Foo()
# @expected-error @below {{invalid call to 'Foo': unexpected argument}}
Foo(True)
# // -----
# ---------------------------------------------------------------------------
# Raw MLIR types (comptime __mlir_type): same rule applies — ambiguous import
# detected at the second import statement.
from mlirtype_a import Foo
# @expected-error @below {{import of 'Foo' is ambiguous}}
from mlirtype_b import Foo
def use_mlirtype[x: Foo]():
pass
# // -----
# ---------------------------------------------------------------------------
# Mixed struct and function: importing a struct and a function with the same
# name is an error — functions and non-functions cannot share a name, matching
# the rule for local declarations.
from struct_c import Foo
# @expected-error @below {{import of 'Foo' is ambiguous}}
from fn_c import Foo
# // -----
# ---------------------------------------------------------------------------
# Mixed function and struct: same rule as above but with the order reversed —
# function imported first, then a struct with the same name. Exercises the
# incomingNonFn+existingFn branch of checkImportNamingConflict.
from fn_d import Foo
# @expected-error @below {{import of 'Foo' is ambiguous}}
from struct_d import Foo
# // -----
# ---------------------------------------------------------------------------
# Duplicate import: importing the same name from the same module twice is
# legal and must not be treated as a conflict — both import statements
# resolve to the same ASTDecl, which is excluded from the existing-set scan
# via the skip parameter in checkImportNamingConflict.
from struct_dup import Foo
from struct_dup import Foo # no error
def use_dup[x: Foo]():
pass
@@ -0,0 +1,118 @@
# ===----------------------------------------------------------------------=== #
# 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.
# ===----------------------------------------------------------------------=== #
# Discharging parametric `where` clauses: witness selection against a
# trait-alias bound and against a same-named method that stays partially bound,
# and a clause that can be neither proven nor refuted at a conversion site.
# RUN: %parse-mojo-isolated -verify-diagnostics %s
# A same-named `__init__` that stays partially bound, with a parametric `where`
# over a dependent member alias, must not be the `Copyable` witness. Checking
# that clause must not require a specialization with an unbound hole in a nested
# `bind_params`.
struct Wrapper[T: Movable, /](
Movable,
Copyable where conforms_to(T, Copyable),
):
# Cannot be the `Copyable` witness: the requirement is
# `__init__(out self, *, copy: Self)`, which offers nothing to infer
# `IterableType` or the origin of `iterable` from. Its `where` clause stays
# parametric, and names `IteratorType[origin_of(iterable)]` -- whose own
# parameter list is a dependent chain (mutability, then an origin whose type
# mentions it).
def __init__[
IterableType: Iterable,
](
ref iterable: IterableType,
out self: Wrapper[IterableType.IteratorType[origin_of(iterable)].Element],
) where conforms_to(
IterableType.IteratorType[origin_of(iterable)].Element, Copyable
):
pass
# The actual witness: provable directly from the conformance constraint.
def __init__(out self, *, copy: Self) where conforms_to(Self.T, Copyable):
pass
# A parameter bound through a parametric trait alias (`F: _fn_trait[dtype]`)
# contributes `identical(F.dtype, dtype)` on the struct. Generated lifecycle
# methods inherit that constraint as a decl-ref, so witness selection must
# assume the remapped struct-parameter facts -- an index-ref never matches
# the decl-ref naming the same parameter.
comptime _fn_trait[dtype: DType] = ImplicitlyCopyable & Deinitable & (
def[w: Int]() -> SIMD[dtype, w]
)
@fieldwise_init
struct HoldsFn[dtype: DType, F: _fn_trait[dtype]](
Deinitable, ImplicitlyCopyable
):
var f: Self.F
# Both kinds of struct-scope assumption at once: an explicit `where` clause and
# a parametric-trait-alias capture constraint. Witness selection needs the
# capture constraint, and the two reach the struct's scope by different routes,
# so both have to survive.
@fieldwise_init
struct HoldsFnBounded[n: Int, dtype: DType, F: _fn_trait[dtype]](
Deinitable, ImplicitlyCopyable
) where n > 0:
var f: Self.F
# A trait method with a *default* implementation, overridden by a struct method
# whose `where` clause follows from the conformance. The default stub must be
# disabled and the struct's method chosen; leaving the stub in place makes both
# candidates viable and the reference ambiguous.
trait DefaultedGreeter:
def greet(self) -> Int:
return 0
struct ConditionalGreeter[T: Movable](
Movable, DefaultedGreeter where conforms_to(T, Copyable)
):
def greet(self) -> Int where conforms_to(Self.T, Copyable):
return 1
# An `@implicit` constructor whose `where` clause is unprovable in the calling
# scope leaves the conversion undecided rather than impossible. Recording that
# as a definitive "not convertible" for the `(Int, Constrained[m])` pair
# poisons the query below, which asks about the same pair from a scope that can
# prove the clause.
struct Constrained[n: Int]:
var v: Int
@implicit
def __init__(out self, x: Int) where Self.n > 0:
self.v = x
# expected-note @below {{function declared here}}
def takes_constrained[n: Int](imm s: Constrained[n]):
pass
def unprovable_at_call[m: Int]():
# expected-error @below {{invalid call to 'takes_constrained': value passed to 's' cannot be converted from 'Int' to 'Constrained[m]'}}
takes_constrained[m](Int(1))
def provable_at_call[m: Int]() where m > 0:
takes_constrained[m](Int(1))
@@ -0,0 +1,271 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
# RUN: %parse-mojo-isolated -verify-diagnostics %s
##===----------------------------------------------------------------------===##
# Constraint Overload Error Reporting Tests
# Tests for error messages when overload resolution fails due to unprovable
# or inconclusive "where" constraints.
##===----------------------------------------------------------------------===##
# Helper function that represent unprovable constraints since they are not
# always_inline("builtin").
# expected-note @below {{cannot evaluate call to non-builtin function declared here}}
def is_prime(x: Int) -> Bool:
return x > 1
# expected-note @below {{cannot evaluate call to non-builtin function declared here}}
def is_square(x: Int) -> Bool:
return x > 0
##===----------------------------------------------------------------------===##
# Inconclusive Constraints - Single Candidate
##===----------------------------------------------------------------------===##
# expected-note @below {{cannot prove constraint}}
def single_fn_constraint[x: Int]()
# expected-note @below {{constraint declared here}}
where is_prime(x):
pass
def test_single_fn_constraint():
# expected-error @below {{invalid call to 'single_fn_constraint': lacking evidence to prove correctness}}
# expected-note @below {{provide evidence for the constraint here to aid in candidate selection}}
single_fn_constraint[2]()
##===----------------------------------------------------------------------===##
# Inconclusive Constraints - Multi Candidate, One Inconclusive, Equal Fitness
##===----------------------------------------------------------------------===##
# expected-note @below {{cannot prove constraint for candidate}}
def multi_fn_one_inconclusive[x: Int]()
# expected-note @below {{constraint declared here}}
where is_prime(x):
pass
# expected-note @below {{candidate is valid but cannot be selected until other candidates are disproved}}
def multi_fn_one_inconclusive[x: Int]()
where x >= 0:
pass
def test_multi_fn_one_inconclusive():
# expected-error @below {{ambiguous call to 'multi_fn_one_inconclusive': lacking evidence to select candidate}}
# expected-note @below {{provide evidence for or against the constraints here to aid in candidate selection}}
multi_fn_one_inconclusive[2]()
##===----------------------------------------------------------------------===##
# Inconclusive Constraints - Multi Candidate, Multi Inconclusive, Equal Fitness
##===----------------------------------------------------------------------===##
# expected-note @below {{cannot prove constraint for candidate}}
def multi_fn_multi_inconclusive[x: Int]()
# expected-note @below {{constraint declared here}}
where is_prime(x):
pass
# expected-note @below {{cannot prove constraint for candidate}}
def multi_fn_multi_inconclusive[x: Int]()
# expected-note @below {{constraint declared here}}
where is_square(x):
pass
def test_multi_fn_multi_inconclusive():
# expected-error @below {{ambiguous call to 'multi_fn_multi_inconclusive': lacking evidence to select candidate}}
# expected-note @below {{provide evidence for or against the constraints here to aid in candidate selection}}
multi_fn_multi_inconclusive[2]()
##===----------------------------------------------------------------------===##
# Inconclusive Constraints - Multi Candidate, Best Fitness Selects Non-Inconclusive
##===----------------------------------------------------------------------===##
@fieldwise_init
struct SourceStruct(Movable where False):
pass
struct TargetStruct(Movable where False):
@implicit
def __init__(out self, s: SourceStruct):
pass
# This candidate will never work, even if we prove the inconclusive constraint.
# It should be skipped in favor of the better candidate.
def multi_fn_best_fitness_ok[x: Int](s: TargetStruct)
where is_prime(x):
pass
# This candidate is selected due to better fitness (IntLiteral is better match).
def multi_fn_best_fitness_ok[x: Int](s: SourceStruct):
pass
def test_multi_fn_best_fitness_ok():
# No error expected - the IntLiteral overload should be selected
multi_fn_best_fitness_ok[2](SourceStruct())
##===----------------------------------------------------------------------===##
# Inconclusive Constraints - Multi Candidate, Inconclusive Has Best Fitness
##===----------------------------------------------------------------------===##
# expected-note @below {{cannot prove constraint}}
def multi_fn_best_fitness_inconclusive[x: Int](a: IntLiteral)
# expected-note @below {{constraint declared here}}
where is_prime(x):
pass
def multi_fn_best_fitness_inconclusive[x: Int](a: Int)
where x >= 0:
pass
def test_multi_fn_best_fitness_inconclusive():
# expected-error @below {{invalid call to 'multi_fn_best_fitness_inconclusive': lacking evidence to prove correctness}}
# expected-note @below {{provide evidence for the constraint here to aid in candidate selection}}
multi_fn_best_fitness_inconclusive[2](2)
##===----------------------------------------------------------------------===##
# Multiple Constraints per Candidate
##===----------------------------------------------------------------------===##
# expected-note @below {{cannot prove constraint for candidate}}
def mixed_constraints[x: Int, y: Int]()
# expected-note @below {{constraint declared here}}
where is_prime(x)
# No errors expected here since the earlier constraint failed.
where y > 0:
pass
# expected-note @below {{candidate is valid but cannot be selected until other candidates are disproved}}
def mixed_constraints[x: Int, y: Int]()
where x >= 0
where y >= 0:
pass
def test_mixed_constraints():
# expected-error @below {{ambiguous call to 'mixed_constraints': lacking evidence to select candidate}}
# expected-note @below {{provide evidence for or against the constraints here to aid in candidate selection}}
mixed_constraints[2, 1]()
##===----------------------------------------------------------------------===##
# Reference to Overloaded Declaration (not a call)
##===----------------------------------------------------------------------===##
# expected-note @below {{cannot prove constraint for candidate}}
def ref_to_overload[x: Int](a: Int32)
# expected-note @below {{constraint declared here}}
where is_prime(x):
pass
# expected-note @below {{candidate is valid but cannot be selected until other candidates are disproved}}
def ref_to_overload[x: Int](a: UInt32)
where x >= 0:
pass
def test_ref_to_overload():
# expected-error @below {{ambiguous call to 'ref_to_overload': lacking evidence to select candidate}}
# expected-note @below {{provide evidence for or against the constraints here to aid in candidate selection}}
ref_to_overload[2]
##===----------------------------------------------------------------------===##
# Multiple Inconclusive Constraints on Same Candidate
##===----------------------------------------------------------------------===##
# expected-note @below {{cannot prove or disprove constraints for candidate}}
def multiple_inconclusive_same[x: Int, y: Int]()
# expected-note @below {{constraint declared here}}
where is_prime(x)
# expected-note @below {{constraint declared here}}
where is_square(y):
pass
def test_multiple_inconclusive_same():
# expected-error @below {{invalid call to 'multiple_inconclusive_same': lacking evidence to prove correctness}}
# expected-note @below {{provide evidence for the constraint here to aid in candidate selection}}
multiple_inconclusive_same[2, 4]()
##===----------------------------------------------------------------------===##
# Combination of Provable and Inconclusive Constraints
##===----------------------------------------------------------------------===##
# expected-note @below {{cannot prove constraint}}
def provable_and_inconclusive[x: Int, y: Int](a: Int32)
where x > 0 # This is provable with literal 2
# expected-note @below {{constraint declared here}}
where is_prime(y): # This is not provable
pass
def provable_and_inconclusive[x: Int](a: UInt32)
where x < 0:
pass
def test_provable_and_inconclusive():
# expected-error @below {{invalid call to 'provable_and_inconclusive': lacking evidence to prove correctness}}
# expected-note @below {{provide evidence for the constraint here to aid in candidate selection}}
provable_and_inconclusive[2, 2](4)
##===----------------------------------------------------------------------===##
# Violated vs Inconclusive Constraints
##===----------------------------------------------------------------------===##
# This candidate has a violated constraint (should be rejected)
def violated_vs_inconclusive[x: Int](a: Int32)
where x > 10: # Violated by x=2
pass
# This candidate has an inconclusive constraint
# expected-note @below {{cannot prove constraint}}
def violated_vs_inconclusive[x: Int](a: UInt32)
# expected-note @below {{constraint declared here}}
where is_prime(x): # Inconclusive for x=2
pass
def test_violated_vs_inconclusive():
# The first candidate should be eliminated due to violated constraint,
# leaving only the inconclusive one which should error
# expected-error @below {{invalid call to 'violated_vs_inconclusive': lacking evidence to prove correctness}}
# expected-note @below {{provide evidence for the constraint here to aid in candidate selection}}
violated_vs_inconclusive[2](4)
##===----------------------------------------------------------------------===##
# Violated Constraint With Dependent Type in Proposition (MOCO-4333)
##===----------------------------------------------------------------------===##
@fieldwise_init
struct Lin(Copyable, Deinitable where False):
pass
# expected-note @below {{function declared here}}
def make[
Keys: Iterable,
# Make sure compiler does not crash when emitting the note, dependent type
# `origin[*(0, 0)]` need to be replaced properly.
#
# expected-note-re @below {{constraint declared here evaluated to False, expected 'conforms_to(Keys.IteratorType[{{.*}}].Element, Deinitable)'}}
](ref keys: Keys) where conforms_to(
Keys.IteratorType[origin_of(keys)].Element, Deinitable
):
pass
def test_dependent_type_violated_constraint():
# expected-error @below {{invalid call to 'make': violated constraint}}
make(List[Lin]())
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,348 @@
# ===----------------------------------------------------------------------=== #
# 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
# ===----------------------------------------------------------------------=== #
# Function decorators
# ===----------------------------------------------------------------------=== #
# Issue #14191
# expected-error @+1 {{unexpected tokens after decorator, each need to be on their own line}}
@always_inline wqeqwe
def issue14191() -> Int:
return 1
def issue1242():
var decorator: Int
@decorator # expected-error {{cannot use a dynamic value in decorator}}
def on_message() capturing: pass
@invalid_dec # expected-error {{use of unknown declaration 'invalid_dec'}}
def unknown_decorator(): pass
def decorator_on_statements() raises:
@invalid_dec
var decorated_var: Int # expected-error {{'var' statement in function body does not support decorators; remove the decorator}}
@invalid_dec
comptime decorated_alias = 42 # expected-error {{'comptime' statement in function body does not support decorators; remove the decorator}}
@invalid_dec
while True: # expected-error {{'while' statement does not support decorators; remove the decorator}}
pass
@invalid_dec
_ = 1 + 1 # expected-error {{statement does not support decorators; remove the decorator}}
# expected-error @+1 {{decorators must be on their own line; add a newline after the decorator}}
@always_inline def same_line_decorator(): pass
# comptime if causes confusing indentation error message
# https://github.com/modularml/modular/issues/19163
def some_fn():
# expected-error @below {{decorators must be on their own line; add a newline after the decorator}}
@decorator if True:
pass
def some_fn_2():
# expected-error @below {{decorator must be followed by a definition on the next line; remove any blank lines between them}}
@decorator
# expected-error @+1 {{statement indentation must match the rest of the block; adjust to align}}
if True: # expected-warning {{'if' condition always evaluates to 'True'; 'else' branch is unreachable}}
pass
@decorator[] # expected-error {{invalid expression in decorator}}
def bad_decorator_expression_1():
pass
@decorator[]() # expected-error {{invalid expression in decorator}}
def bad_decorator_expression_2():
pass
@567 # expected-error {{invalid expression in decorator}}
def bad_decorator_expression_3():
pass
# ===----------------------------------------------------------------------=== #
# @always_inline
# ===----------------------------------------------------------------------=== #
@always_inline("builtin", "nodebug") # expected-error {{'@always_inline' decorator takes 0 or 1 arguments, found 2}}
def bad_always_inline_1():
pass
@always_inline(123) # expected-error {{'@always_inline' operand must be "nodebug" or "builtin"}}
def bad_always_inline_2():
pass
@always_inline("no_debug") # expected-error {{'@always_inline' operand must be "nodebug" or "builtin"}}
def bad_always_inline_3():
pass
# ===----------------------------------------------------------------------=== #
# @inline
# ===----------------------------------------------------------------------=== #
@inline # expected-error {{'@inline' decorator takes exactly 1 argument, found 0}}
def bad_inline_1():
pass
@inline(.always, .never) # expected-error {{'@inline' decorator takes exactly 1 argument, found 2}}
def bad_inline_2():
pass
@inline(99) # expected-error {{cannot implicitly convert 'IntLiteral[99]' value to 'InlineLevel'}}
def bad_inline_3():
pass
# COM: 3 is the compiler's AlwaysBuiltin, which needs @always_inline("builtin").
@inline(3) # expected-error {{cannot implicitly convert 'IntLiteral[3]' value to 'InlineLevel'}}
def bad_inline_4():
pass
@inline("always") # expected-error {{'@inline' argument must be an InlineLevel, not a string; use '.always', '.nodebug', '.never' or '.automatic'}}
def bad_inline_5():
pass
@inline(level=.always) # expected-error {{'@inline' argument must be positional}}
def bad_inline_6():
pass
# COM: Decorators are applied bottom-up, so the upper one is the one rejected.
@no_inline # expected-error {{function has conflicting inline level from a previous '@inline' decorator}}
@inline(.always)
def bad_inline_7():
pass
@inline(.never) # expected-error {{function has conflicting inline level from a previous '@inline' decorator}}
@inline(.always)
def bad_inline_8():
pass
@always_inline # expected-error {{function has conflicting inline level from a previous '@inline' decorator}}
@inline(.never)
def bad_inline_9():
pass
# ===----------------------------------------------------------------------=== #
# @staticmethod
# ===----------------------------------------------------------------------=== #
@staticmethod # expected-error {{only methods on structs may be declared static}}
def not_a_struct_method(): pass
struct HasBadStaticMethod(Movable where False):
@staticmethod() # expected-error {{'@staticmethod' cannot have arguments}}
def bad_static_method_1(): pass
@staticmethod("abc") # expected-error {{'@staticmethod' cannot have arguments}}
def bad_static_method_2(): pass
# ===----------------------------------------------------------------------=== #
# @no_inline
# ===----------------------------------------------------------------------=== #
@no_inline() # expected-error {{'@no_inline' cannot have arguments}}
def bad_no_inline_1() raises:
pass
@no_inline("abc") # expected-error {{'@no_inline' cannot have arguments}}
def bad_no_inline_2():
pass
# ===----------------------------------------------------------------------=== #
# @implicit
# ===----------------------------------------------------------------------=== #
struct CheckImplicit(Movable where False):
# expected-error @+1 {{'@implicit' may only be applied to '__init__' methods}}
@implicit
def foo(mut self): pass
# expected-error @+2 {{'@implicit' initializers must accept a single positional argument value}}
@implicit
def __init__(out self): pass
# expected-error @+2 {{'@implicit' initializers must accept a single positional argument value}}
@implicit
def __init__(out self, x: Int, y: Int): pass
# expected-error @+2 {{'@implicit' initializers must accept a single positional argument value}}
@implicit
def __init__(out self, *, z: Int): pass
# expected-error @+1 {{'@implicit' may only be applied to '__init__' methods}}
@implicit
def __init__(out self, *, copy: Self): pass
# expected-error @+1 {{'@implicit' decorator takes 0 or 1 arguments, found 2}}
@implicit(123, "abc")
def __init__(out self, a: Int): pass
# expected-error @+1 {{'@implicit' may only have a keyword argument 'deprecated' with literal boolean value}}
@implicit(123)
def __init__(out self, *, a: Int): pass
# expected-error @+1 {{'@implicit' may only have a keyword argument 'deprecated' with literal boolean value}}
@implicit(deprecated=123)
def __init__(out self, b: String): pass
# expected-error @+1 {{'@implicit' may only have a keyword argument 'deprecated' with literal boolean value}}
@implicit(foo=True)
def __init__(out self, c: Bool): pass
struct DeprecatedImplicitConversion(Movable where False):
# expected-note @+2 {{implicit constructor for 'DeprecatedImplicitConversion' declared here}}
@implicit(deprecated=True)
def __init__(out self, value: Int):
pass
def foo(y: DeprecatedImplicitConversion): pass
def foo(z: String): pass
def deprecated_implicit_conversion():
# expected-warning @+2 {{deprecated implicit conversion from 'IntLiteral[1]' to 'DeprecatedImplicitConversion'}}
# expected-note @+1 {{call 'DeprecatedImplicitConversion(...)' explicitly}}
_: DeprecatedImplicitConversion = 1
# expected-warning @+2 {{deprecated implicit conversion from 'Int' to 'DeprecatedImplicitConversion'}}
# expected-note @+1 {{call 'DeprecatedImplicitConversion(...)' explicitly}}
foo(Int(1))
# ===----------------------------------------------------------------------=== #
# @extern
# ===----------------------------------------------------------------------=== #
@extern # expected-error {{'@extern' requires 1 argument}}
def bad_extern_1(): ...
@extern() # expected-error {{'@extern' requires 1 argument}}
def bad_extern_2(): ...
@extern(123) # expected-error {{'@extern' requires a string literal argument}}
def bad_extern_3(): ...
@extern("bad_extern", "bad_extern_3") # expected-error {{'@extern' requires 1 argument}}
def bad_extern_4(): ...
# expected-error @+2 {{unexpected function body in extern function declaration, use `...`}}
@extern("add_one")
def my_extern_add_one(x: Int) abi("Mojo") -> Int:
return x + 1
struct HasExtern(Movable where False):
# expected-error @+1 {{'@extern' cannot be applied to a method}}
@extern("add_one_struct")
def my_extern_struct_add_one(self, x: Int) -> Int:
...
# expected-error @+1 {{'@extern' requires an explicit 'abi()' effect on the function}}
@extern("no_abi_extern")
def extern_missing_abi(): ...
# ===----------------------------------------------------------------------=== #
# @__llvm_metadata
# ===----------------------------------------------------------------------=== #
@__llvm_metadata # expected-error {{'@__llvm_metadata' requires operands}}
def llvm_meta_no_arg_1[x: Int](a: Int, b: Int):
pass
@__llvm_metadata() # expected-error {{'@__llvm_metadata' requires operands}}
def llvm_meta_no_arg_2[x: Int](a: Int, b: Int):
pass
# ===----------------------------------------------------------------------=== #
# @__llvm_arg_metadata
# ===----------------------------------------------------------------------=== #
@__llvm_arg_metadata # expected-error {{'@__llvm_arg_metadata' requires operands}}
def llvm_arg_meta_no_arg_1[x: Int](a: Int, b: Int):
pass
@__llvm_arg_metadata() # expected-error {{'@__llvm_arg_metadata' requires operands}}
def llvm_arg_meta_no_arg_2[x: Int](a: Int, b: Int):
pass
# expected-error @+1 {{First argument of '@__llvm_arg_metadata' must be an argument name}}
@__llvm_arg_metadata(1 + 1)
def llvm_arg_meta_wrong_type[x: Int](a: Int, b: Int):
pass
# expected-error @+1 {{Function decorated by '@__llvm_arg_metadata' has no argument named 'c'}}
@__llvm_arg_metadata(c, myMeta)
def llvm_arg_meta_wrong_name[x: Int](a: Int, b: Int):
pass
# ===----------------------------------------------------------------------=== #
# Closure decorators
# ===----------------------------------------------------------------------=== #
def outer_function():
@__copy_capture # expected-error {{'@__copy_capture' must have arguments}}
@__parameter() # expected-error {{'@__parameter' cannot have arguments}}
def copy_capture_no_args_1():
pass
@__copy_capture() # expected-error {{'@__copy_capture' must have arguments}}
@__parameter("abc") # expected-error {{'@__parameter' cannot have arguments}}
def copy_capture_no_args_2():
pass
@__move_capture # expected-error {{'@__move_capture' must have arguments}}
@__parameter
def move_capture_no_args_1():
pass
@__move_capture() # expected-error {{'@__move_capture' must have arguments}}
@__parameter
def move_capture_no_args_2():
pass
# ===----------------------------------------------------------------------=== #
# Struct decorators
# ===----------------------------------------------------------------------=== #
@invalid_dec # expected-error {{use of unknown declaration 'invalid_dec'}}
struct BadStructDecorator(Movable where False): pass
struct DecoratorSameLine(Movable where False):
# expected-error @+1 {{decorators must be on their own line; add a newline after the decorator}}
@staticmethod def same_line_decorator(): pass
@fieldwise_init # expected-error {{'FieldwiseInitExample' has an explicitly declared fieldwise initializer}}
struct FieldwiseInitExample[T: Movable & Deinitable](Movable where False):
var x: Int
var y: Self.T
# expected-note @below {{initializer declared here}}
def __init__(out self, x: Int, y: Self.T):
pass
# ===----------------------------------------------------------------------=== #
# Trait decorators
# ===----------------------------------------------------------------------=== #
@decorator # expected-error {{unrecognized body decorators}}
trait NoDecorators:
pass
@@ -0,0 +1,280 @@
# ===----------------------------------------------------------------------=== #
# 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 @deprecated decorator warning emission.
# RUN: %parse-mojo-isolated -verify-diagnostics %s -I=%S/inputs
# ===----------------------------------------------------------------------=== #
# Test declarations
# ===----------------------------------------------------------------------=== #
@deprecated("deprecated struct")
# expected-note @below {{'DeprecatedStruct' declared here}}
struct DeprecatedStruct(Movable where False):
pass
@deprecated("deprecated function")
# expected-note @below {{'deprecated_fn' declared here}}
def deprecated_fn():
pass
def normal_fn():
pass
@deprecated("deprecated trait")
# expected-note @below {{'DeprecatedTrait' declared here}}
trait DeprecatedTrait:
pass
trait NormalTrait:
pass
@deprecated("deprecated alias")
# Note: The note format for aliases includes a suffix like `0x, so we use
# expected-note-re to match it. See MOCO-3108.
# expected-note-re @below {{'deprecated_alias{{.*}}' declared here}}
comptime deprecated_alias = 42
comptime normal_alias = 42
struct StructWithDeprecatedMembers(Movable where False):
# Note: @deprecated on fields is not supported - decorators cannot be applied
# to `var` statements. This is a parser-level limitation.
def __init__(out self):
pass
@deprecated("deprecated method")
# expected-note @below {{'deprecated_method' declared here}}
def deprecated_method(self):
pass
def normal_method(self):
pass
# ===----------------------------------------------------------------------=== #
# Test: Deprecated struct as type annotation
# ===----------------------------------------------------------------------=== #
# expected-warning @below {{deprecated struct}}
def use_deprecated_struct_in_signature(value: DeprecatedStruct):
pass
# ===----------------------------------------------------------------------=== #
# Test: Deprecated function call
# ===----------------------------------------------------------------------=== #
def test_deprecated_function_call():
# expected-warning @below {{deprecated function}}
deprecated_fn()
# No warning expected.
normal_fn()
# ===----------------------------------------------------------------------=== #
# Test: Deprecated function reference (not call)
# ===----------------------------------------------------------------------=== #
def takes_fn_ref(f: def() thin -> None):
f()
def test_deprecated_function_reference():
# Taking a reference to a deprecated function also emits the deprecation warning.
# expected-warning @below {{deprecated function}}
var f = deprecated_fn
takes_fn_ref(f)
# No warning expected.
var g = normal_fn
takes_fn_ref(g)
# ===----------------------------------------------------------------------=== #
# Test: Deprecated trait conformance
# ===----------------------------------------------------------------------=== #
# expected-warning @below {{deprecated trait}}
struct StructConformingToDeprecatedTrait(DeprecatedTrait, Movable where False):
pass
struct StructConformingToNormalTrait(NormalTrait, Movable where False):
# No warning expected.
pass
# ===----------------------------------------------------------------------=== #
# Test: Deprecated alias usage
# ===----------------------------------------------------------------------=== #
def test_deprecated_alias():
# expected-warning @below {{deprecated alias}}
_ = deprecated_alias
# No warning expected.
_ = normal_alias
# ===----------------------------------------------------------------------=== #
# Test: Deprecated method call
# ===----------------------------------------------------------------------=== #
def test_deprecated_method_call():
var obj = StructWithDeprecatedMembers()
# expected-warning @below {{deprecated method}}
obj.deprecated_method()
# No warning expected.
obj.normal_method()
# ===----------------------------------------------------------------------=== #
# Test: Deprecated method reference (not call)
# ===----------------------------------------------------------------------=== #
def test_deprecated_method_reference():
# Taking a reference to a deprecated method emits the deprecation warning.
# expected-warning @below {{deprecated method}}
_ = StructWithDeprecatedMembers.deprecated_method
# No warning expected.
_ = StructWithDeprecatedMembers.normal_method
# ===----------------------------------------------------------------------=== #
# Test: Deprecated function overload
# ===----------------------------------------------------------------------=== #
@deprecated("deprecated overload")
# expected-note @below {{'overloaded_fn' declared here}}
def overloaded_fn():
pass
# expected-warning @below {{deprecated struct}}
def overloaded_fn(value: DeprecatedStruct):
pass
def test_deprecated_function_overload():
# expected-warning @below {{deprecated overload}}
overloaded_fn()
# ===----------------------------------------------------------------------=== #
# Test: @deprecated decorator errors
# ===----------------------------------------------------------------------=== #
# expected-error @below {{@deprecated requires a reason message}}
@deprecated
def no_message():
pass
comptime NOT_A_STRING = 123
# expected-error @below {{'reason' argument must be a string literal}}
@deprecated(NOT_A_STRING)
def deprecated_with_non_string_reason():
pass
# expected-error @below {{'reason' argument must be a string literal}}
@deprecated(reason=NOT_A_STRING)
def deprecated_with_non_string_keyword_reason():
pass
# ===----------------------------------------------------------------------=== #
# Test: @deprecated and @stable mutual exclusivity
# ===----------------------------------------------------------------------=== #
# Both decorators cannot be used together.
@deprecated("use something else")
# expected-error @below {{@deprecated and @stable cannot be used together}}
@stable
def deprecated_and_stable():
pass
# Order does not matter - still an error.
@stable
# expected-error @below {{@deprecated and @stable cannot be used together}}
@deprecated("use something else")
def stable_and_deprecated():
pass
# Another decorator in between does not matter - still an error.
@deprecated("use something else")
@no_inline
# expected-error @below {{@deprecated and @stable cannot be used together}}
@stable
def deprecated_other_stable():
pass
# ===----------------------------------------------------------------------=== #
# Test: @deprecated(use=...) for methods
# ===----------------------------------------------------------------------=== #
def some_top_level_func():
pass
struct InstanceMethodRefTopLevel(Movable where False):
# Instance methods cannot reference top-level functions as replacements.
# expected-error @below {{cannot reference unknown value 'some_top_level_func'}}
@deprecated(use=some_top_level_func)
def instance_method(self):
pass
# ===----------------------------------------------------------------------=== #
# Test: Cross-module deprecation warnings
# ===----------------------------------------------------------------------=== #
from imported_module import DeprecatedInAnotherModule
# expected-warning @below {{use of deprecated struct 'DeprecatedInAnotherModule'}}
def use_deprecated_import(value: DeprecatedInAnotherModule):
pass
@@ -0,0 +1,21 @@
# ===----------------------------------------------------------------------=== #
# 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.
# ===----------------------------------------------------------------------=== #
# Module imported by deprecated_errors.mojo to test cross-module deprecation warnings.
@deprecated("use of deprecated struct 'DeprecatedInAnotherModule'")
# expected-note @below {{'DeprecatedInAnotherModule' declared here}}
struct DeprecatedInAnotherModule(Movable where False):
pass
@@ -0,0 +1,27 @@
# ===----------------------------------------------------------------------=== #
# 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 -I=%S/inputs
# expected-error @+2 {{@__doc_inline is not supported on wildcard imports}}
@__doc_inline
from target_module import *
# A rename would publish the source name against the destination name.
# expected-error @+2 {{@__doc_inline is not supported on renamed imports ('import ... as ...')}}
@__doc_inline
from target_module import InlinedStruct as RenamedStruct
# expected-error @+1 {{'from' statement supports only the @stable and @__doc_inline decorators; remove the decorator}}
@not_a_real_decorator
from target_module import InlinedStruct
@@ -0,0 +1,68 @@
# ===----------------------------------------------------------------------=== #
# 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
# expected-warning @+1 {{@export requires an explicit 'abi()' effect on the function}}
@export("noabi")
def no_abi():
...
# expected-error @+2 {{'abi("C")' function may not be marked 'raises'; remove 'raises' or use 'abi("Mojo")'}}
@export("c_raises")
def c_raises() abi("C") raises:
...
# expected-error @+1 {{@export requires a string specifying the name of the exported symbol}}
@export(1)
def export_me() abi("C"):
...
# expected-note @+1 {{previous export here}}
@export("my_foo")
def foo() abi("C"):
...
# expected-error @+1 {{invalid re-export of my_foo}}
@export("my_foo")
def bar() abi("C"):
...
# expected-warning @+2 {{ABI="C" is deprecated; use abi("C") instead}}
# expected-error @+1 {{my+foo is not a valid C identifier}}
@export("my+foo", ABI="C")
def bad_name():
...
# expected-warning @+2 {{ABI="C" is deprecated; use abi("C") instead}}
# expected-error @+1 {{'abi("C")' function may not be marked 'raises'; remove 'raises' or use 'abi("Mojo")'}}
@export("c_raises", ABI="C")
def c_raises_old_abi() raises:
...
# expected-note @+1 {{previous export here}}
@export
def func_overloaded(x: Int) abi("C"):
...
# expected-error @+1 {{invalid re-export of func_overloaded}}
@export
def func_overloaded(x: Bool) abi("C"):
...
@@ -0,0 +1,22 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
struct DTypePointer(Movable where False):
pass
@deprecated("use of deprecated struct 'DeprecatedInAnotherModule'")
# expected-note @below {{'DeprecatedInAnotherModule' declared here}}
struct DeprecatedInAnotherModule(Movable where False):
pass
@@ -0,0 +1,48 @@
# ===----------------------------------------------------------------------=== #
# 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
# expected-error @+1 {{@__name must have at least 1 argument}}
@__name
def name_no_args():
...
# expected-error @+1 {{@__name must have at most 1 name argument}}
@__name("name1", "name2")
def name_two_args():
...
# expected-error @+1 {{function has conflicting linkage name from a previous @__name or @export decorator}}
@__name("first_name")
@export("different_name")
def name_export_conflict() abi("C"):
...
# expected-error @+1 {{function has conflicting linkage name from a previous @__name or @export decorator}}
@export("first_name")
@__name("different_name")
def export_name_conflict() abi("C"):
...
# expected-warning @+2 {{ABI="C" is deprecated; use abi("C") instead}}
# expected-error @+1 {{function has conflicting linkage name from a previous @__name or @export decorator}}
@export("one_name", ABI="C")
@__name("different_name")
def c_export_name_conflict():
...
@@ -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 -mojo-search-paths=%S -verify-diagnostics %s
# Test error cases for @stable decorator.
#
# Note: Tests for "@stable member in unstable struct/trait" are located in
# test_std_mock/__init__.mojo since those errors only apply in opted-in packages.
# Error: @stable with a positional (non-keyword) argument is not supported.
# expected-error @+1 {{@stable requires a keyword argument ('since' or 'recursive'), not a positional argument}}
@stable("since 1.0")
struct StableWithArg(Movable where False):
pass
# Error: @stable on local variable is not supported.
def test_local_var():
# expected-error @+2 {{'var' statement in function body does not support decorators; remove the decorator}}
@stable
var x = 1
# @stable on comptime is now supported (as of escape hatches feature).
# Verify it doesn't error - this alias will be verified in a separate test.
@stable
comptime MY_STABLE_ALIAS = 42
# Verify that @stable members in stable structs are allowed (no error).
@stable
struct LocalStableStruct(Movable where False):
@stable
def stable_method_in_stable(self):
pass
# Verify that @stable members in stable traits are allowed (no error).
@stable
trait StableTrait:
@stable
def stable_method_in_stable_trait(self): ...
# Verify that @stable members in non-opted-in package types are allowed.
# This file is not in an opted-in package, so structs/traits here are stable
# by default, and @stable members should be allowed.
struct StructInNonOptedInPackage(Movable where False):
@stable
def stable_method(self):
pass
trait TraitInNonOptedInPackage:
@stable
def stable_method(self): ...
# Error: @stable on wildcard import is not supported.
# expected-error @+2 {{@stable(recursive=True) is not supported on wildcard imports}}
@stable(recursive=True)
from test_std_mock import *
# Error: bare @stable on import requires recursive=True argument.
# expected-error @+1 {{@stable on import requires 'recursive=True' argument}}
@stable
from test_std_mock import StableStruct
# Error: @stable(recursive=False) is not supported.
# expected-error @+1 {{'recursive' argument to @stable must be True}}
@stable(recursive=False)
from test_std_mock import StableStruct
# Error: @stable(recursive=<non-bool>) is not supported.
# expected-error @+1 {{'recursive' argument to @stable must be True}}
@stable(recursive="yes")
from test_std_mock import StableStruct
@@ -0,0 +1,65 @@
# ===----------------------------------------------------------------------=== #
# 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
# Test error cases for @stable(since=...) argument.
# Error: positional string argument — only keyword 'since' is accepted.
# expected-error @+1 {{@stable requires a keyword argument ('since' or 'recursive'), not a positional argument}}
@stable("1.0")
def fn_positional_string():
pass
# Error: unknown keyword argument.
# expected-error @+1 {{@stable only accepts keyword arguments 'since' or 'recursive'}}
@stable(unknown="1.0")
def fn_unknown_kwarg():
pass
# Error: since= value must be a string literal, not a number.
# expected-error @+1 {{'since' argument must be a string literal}}
@stable(since=1)
def fn_since_not_string():
pass
# Error: version string must start with a digit.
# expected-error @+1 {{'since' argument must be a valid version string}}
@stable(since="v1.0")
def fn_since_starts_with_letter():
pass
# Error: empty version string.
# expected-error @+1 {{'since' argument must be a valid version string}}
@stable(since="")
def fn_since_empty():
pass
# Error: version string with invalid characters (hyphen is not allowed).
# expected-error @+1 {{'since' argument must be a valid version string}}
@stable(since="1.0-alpha")
def fn_since_hyphen():
pass
# Error: too many arguments.
# expected-error @+1 {{@stable accepts only one argument, either 'since' or 'recursive'}}
@stable(since="1.0", extra="x")
def fn_too_many_args():
pass
@@ -0,0 +1,276 @@
# ===----------------------------------------------------------------------=== #
# 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.
# ===----------------------------------------------------------------------=== #
# Mock package for testing stability marker warnings.
# This package is opted into stability markers (alongside "std"), so unstable
# APIs here will trigger warnings when used from outside the package.
@stable
struct StableStruct(Movable where False):
"""A stable struct that should not trigger warnings."""
def __init__(out self):
pass
struct UnstableStruct(Movable):
"""An unstable struct that should trigger warnings when used."""
comptime UNSTABLE_CONST: Int = 99
def __init__(out self):
"""Unstable constructor."""
pass
def unstable_method(self) -> Int:
"""An unstable method that should trigger warnings when called."""
return 42
comptime AliasedType = AnotherUnstableStruct
struct AnotherUnstableStruct(Movable where False):
"""A second unstable struct, exposed via a comptime alias in UnstableStruct.
"""
def __init__(out self):
pass
@staticmethod
def static_method() -> Int:
return 0
@stable
def stable_fn():
"""A stable function that should not trigger warnings."""
pass
def unstable_fn():
"""An unstable function that should trigger warnings when called."""
pass
@stable
trait StableTrait:
"""A stable trait that should not trigger warnings when implemented."""
pass
trait UnstableTrait:
"""An unstable trait that should trigger warnings when implemented."""
pass
trait UnstableTraitWithMembers:
"""An unstable trait with a default-impl method and an associated comptime.
"""
comptime ASSOC_TYPE = Int
def default_method(self) -> Int:
return 42
@stable
struct StructWithMethods(Movable where False):
"""A stable struct with both stable and unstable methods."""
var value: Int
@stable
def __init__(out self):
self.value = 0
@stable
def stable_method(self) -> Int:
return self.value
def unstable_method(self) -> Int:
return self.value
@stable
trait TraitWithStableMethod:
"""A stable trait with a stable method requirement."""
@stable
def stable_required_method(self) -> Int:
...
@stable
trait TraitWithUnstableMethod:
"""A stable trait with an unstable method requirement."""
def unstable_required_method(self) -> Int:
...
# Extension of UnstableStruct with an additional unstable method, for testing
# that @stable(recursive=True) suppresses warnings on extension-defined members.
__extension UnstableStruct:
def extension_method(self) -> Int:
"""An unstable extension method on UnstableStruct."""
return 99
# Test same-package usage: stable functions calling unstable functions internally.
# This should NOT trigger warnings because both are in the same opted-in package.
@stable
def stable_fn_using_unstable() -> Int:
"""A stable function that internally calls unstable APIs.
When a user calls this stable function, they should NOT see warnings about
the internal usage of unstable APIs. The intra-package usage is allowed.
"""
# These internal calls to unstable APIs should NOT warn (same package).
unstable_fn()
var s = UnstableStruct()
return s.unstable_method()
# Alias tests for escape hatches feature.
# Stable alias re-exporting an unstable struct - users should not get warning.
@stable
comptime StableAliasToUnstable = UnstableStruct
# Unstable alias - users should get warning when using this.
comptime UnstableAlias = StableStruct
# Stable constant alias.
@stable
comptime STABLE_CONSTANT: Int = 42
# Unstable constant alias.
comptime UNSTABLE_CONSTANT: Int = 100
# For testing: stable struct implementing stable trait with stable method.
# The struct's implementing method SHOULD be stable. If not, API author gets warning.
@stable
struct StableStructWithStableImpl(TraitWithStableMethod, Movable where False):
@stable
def stable_required_method(self) -> Int:
return 1
# For testing: stable struct implementing stable trait with UNSTABLE method.
# This SHOULD warn the API author (always, not just with --warn-on-unstable-apis).
# The warning is tested by warn_api_author.mojo using FileCheck.
@stable
struct StableStructWithUnstableImpl(TraitWithStableMethod, Movable where False):
# Not marked @stable - this should warn!
def stable_required_method(self) -> Int:
return 2
@stable
struct StableStructWithMovable(Movable):
var val: Int
# For testing stable function return type check.
# This stable function returns an unstable type - should warn API author.
# The warning is tested by warn_api_author.mojo using FileCheck.
@stable
def stable_fn_returning_unstable() -> UnstableStruct:
return UnstableStruct()
# For comparison: stable function returning stable type - no warning.
@stable
def stable_fn_returning_stable() -> StableStruct:
return StableStruct()
# For testing: stable trait inheriting from unstable trait - should warn API author.
# This is invalid because a stable trait cannot have unstable parents.
# The warning is tested by warn_api_author.mojo using FileCheck.
@stable
trait StableTraitWithUnstableParent(UnstableTrait):
pass
# For comparison: stable trait inheriting from stable trait - no warning.
@stable
trait StableTraitWithStableParent(StableTrait):
pass
# ===----------------------------------------------------------------------===
# Alias stability tests for trait conformance
# ===----------------------------------------------------------------------===
@stable
trait TraitWithStableAlias:
"""A stable trait with a stable comptime alias requirement."""
@stable
# expected-note-re @below {{trait alias 'Value{{.*}}' in 'TraitWithStableAlias' is marked @stable}}
comptime Value: Int
# For testing: stable struct implementing stable trait with UNSTABLE alias.
# This SHOULD warn the API author (analogous to StableStructWithUnstableImpl).
@stable
struct StableStructWithUnstableAliasImpl(TraitWithStableAlias, Movable where False):
# Note: The alias name includes a suffix like `Value`1` due to internal naming.
# expected-warning-re @below {{stable struct 'StableStructWithUnstableAliasImpl' implements stable trait alias 'Value{{.*}}' with unstable implementation}}
comptime Value: Int = 42
def __init__(out self):
pass
# For comparison: stable struct with stable alias implementation - no warning.
@stable
struct StableStructWithStableAliasImpl(TraitWithStableAlias, Movable where False):
@stable
comptime Value: Int = 100
def __init__(out self):
pass
# ===----------------------------------------------------------------------===
# Error cases: @stable member in unstable struct/trait
# ===----------------------------------------------------------------------===
# These test that @stable members cannot be declared in unstable types.
# Since this package is opted-in, types without @stable are unstable.
struct UnstableStructWithStableMember(Movable where False):
"""An unstable struct that incorrectly has a @stable member."""
def __init__(out self):
pass
# expected-warning@+1 {{@stable member cannot be declared in an unstable struct}}
@stable
def stable_method_in_unstable(self):
pass
trait UnstableTraitWithStableMember:
"""An unstable trait that incorrectly has a @stable member."""
# expected-warning@+1 {{@stable member cannot be declared in an unstable trait}}
@stable
def stable_method_in_unstable_trait(self):
...
@@ -0,0 +1,31 @@
# ===----------------------------------------------------------------------=== #
# 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 --warn-on-unstable-apis emits warnings when unstable magic functions
# are used. Some magic functions (origin_of, type_of, conforms_to,
# __functions_in_module) are considered stable and should not warn.
# RUN: %parse-mojo-isolated -warn-on-unstable-apis -verify-diagnostics %s
def test_stable_magic_functions():
"""Stable magic functions should NOT trigger warnings."""
var x = 42
# type_of, origin_of, conforms_to, __functions_in_module are stable.
comptime t = type_of(x)
def test_unstable_get_current_function_name():
"""Using __get_current_function_name should trigger an unstable warning."""
# expected-warning @+1 {{use of unstable function '__get_current_function_name'}}
comptime name = __get_current_function_name()
@@ -0,0 +1,22 @@
# ===----------------------------------------------------------------------=== #
# 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.
# ===----------------------------------------------------------------------=== #
# Module imported by unavailable_errors.mojo to test cross-module
# unavailability errors.
@unavailable("use of unavailable function in another module")
# expected-note @below {{'unavailable_in_another_module' declared here}}
def unavailable_in_another_module():
...
@@ -0,0 +1,72 @@
# ===----------------------------------------------------------------------=== #
# 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 that @unavailable functions accept '...' as their body even when they
# have a non-None return type, and reject any other body content.
# RUN: %parse-mojo-isolated -verify-diagnostics %s
# ===----------------------------------------------------------------------=== #
# Test: '...' body is accepted for @unavailable function with no return type
# ===----------------------------------------------------------------------=== #
@unavailable("don't use")
def ok_unavailable_void():
...
# ===----------------------------------------------------------------------=== #
# Test: '...' body is accepted for @unavailable function with a return type
# ===----------------------------------------------------------------------=== #
@unavailable("don't use")
def ok_unavailable_int_return() -> Int:
...
@unavailable("don't use")
def ok_unavailable_string_return() -> String:
...
# ===----------------------------------------------------------------------=== #
# Test: '...' body is accepted for @unavailable method with a return type
# ===----------------------------------------------------------------------=== #
struct StringLike(Movable where False):
@unavailable("no length for 'StringLike'; use byte_length() or codepoint_length() instead")
def __len__(self) -> Int:
...
# ===----------------------------------------------------------------------=== #
# Test: non-'...' body is rejected on @unavailable function
# ===----------------------------------------------------------------------=== #
@unavailable("don't use")
# expected-note @below {{in 'rejects_pass_body', declared here}}
def rejects_pass_body():
# expected-error @below {{unexpected function body in @unavailable function declaration, use '...'}}
pass
@unavailable("don't use")
# expected-note @below {{in 'rejects_return_body', declared here}}
def rejects_return_body() -> Int:
# expected-error @below {{unexpected function body in @unavailable function declaration, use '...'}}
return 42
@@ -0,0 +1,305 @@
# ===----------------------------------------------------------------------=== #
# 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 @unavailable decorator error emission.
# RUN: %parse-mojo-isolated -verify-diagnostics %s -I=%S/inputs
# ===----------------------------------------------------------------------=== #
# Test declarations
# ===----------------------------------------------------------------------=== #
@unavailable("unavailable function")
# expected-note @below {{'unavailable_fn' declared here}}
def unavailable_fn():
...
def normal_fn():
pass
struct StructWithUnavailableMembers(Movable where False):
def __init__(out self):
pass
@unavailable("unavailable method")
# expected-note @below {{'unavailable_method' declared here}}
def unavailable_method(self):
...
def normal_method(self):
pass
# ===----------------------------------------------------------------------=== #
# Test: Unavailable function call
# ===----------------------------------------------------------------------=== #
def test_unavailable_function_call():
# expected-error @below {{unavailable function}}
unavailable_fn()
# No error expected.
normal_fn()
# ===----------------------------------------------------------------------=== #
# Test: Unavailable function reference (not call)
# ===----------------------------------------------------------------------=== #
def takes_fn_ref(f: def() thin -> None):
f()
def test_unavailable_function_reference():
# Taking a reference to an unavailable function also emits the error.
# expected-error @below {{unavailable function}}
var f = unavailable_fn
takes_fn_ref(f)
# No error expected.
var g = normal_fn
takes_fn_ref(g)
# ===----------------------------------------------------------------------=== #
# Test: Unavailable method call
# ===----------------------------------------------------------------------=== #
def test_unavailable_method_call():
var obj = StructWithUnavailableMembers()
# expected-error @below {{unavailable method}}
obj.unavailable_method()
# No error expected.
obj.normal_method()
# ===----------------------------------------------------------------------=== #
# Test: Unavailable method reference (not call)
# ===----------------------------------------------------------------------=== #
def test_unavailable_method_reference():
# Taking a reference to an unavailable method also emits the error.
# expected-error @below {{unavailable method}}
_ = StructWithUnavailableMembers.unavailable_method
# No error expected.
_ = StructWithUnavailableMembers.normal_method
# ===----------------------------------------------------------------------=== #
# Test: @unavailable is rejected on non-function/method declarations
# ===----------------------------------------------------------------------=== #
# expected-error @below {{@unavailable can only be applied to functions and methods}}
@unavailable("not allowed on structs")
struct StructNotAllowed(Movable where False):
pass
# expected-error @below {{@unavailable can only be applied to functions and methods}}
@unavailable("not allowed on traits")
trait TraitNotAllowed:
pass
# expected-error @below {{@unavailable can only be applied to functions and methods}}
@unavailable("not allowed on aliases")
comptime alias_not_allowed = 42
# `use=` form is also rejected on non-function/method decls.
def replacement_for_struct():
pass
# expected-error @below {{@unavailable can only be applied to functions and methods}}
@unavailable(use=replacement_for_struct)
struct StructUseNotAllowed(Movable where False):
pass
# ===----------------------------------------------------------------------=== #
# Test: @unavailable decorator errors
# ===----------------------------------------------------------------------=== #
# expected-error @below {{@unavailable requires a reason message}}
@unavailable
def no_message():
...
comptime NOT_A_STRING = 123
# expected-error @below {{'reason' argument must be a string literal}}
@unavailable(NOT_A_STRING)
def unavailable_with_non_string_reason():
...
# A `reason=` keyword is accepted (mirrors @deprecated).
@unavailable(reason="reason keyword works")
# expected-note @below {{'unavailable_with_reason_keyword' declared here}}
def unavailable_with_reason_keyword():
...
def test_reason_keyword():
# expected-error @below {{reason keyword works}}
unavailable_with_reason_keyword()
# `reason=` still requires a string literal.
# expected-error @below {{'reason' argument must be a string literal}}
@unavailable(reason=NOT_A_STRING)
def unavailable_with_non_string_reason_keyword():
...
# Multiple positional args are rejected.
# expected-error @below {{@unavailable accepts either a reason message or a replacement symbol (with 'use')}}
@unavailable("msg1", "msg2")
def unavailable_with_too_many_args():
...
# Unrecognized keywords are rejected.
# expected-error @below {{unavailable must specify either a message or a symbol (with the 'use' argument)}}
@unavailable(message="x")
def unavailable_with_unknown_keyword():
...
# `use=` requires a symbol reference, not a literal.
@unavailable(
# expected-error @below {{'use' must reference a symbol}}
use="not_a_symbol"
)
def unavailable_with_string_use():
...
# ===----------------------------------------------------------------------=== #
# Test: @unavailable mutual exclusivity with @deprecated and @stable
# ===----------------------------------------------------------------------=== #
@unavailable("don't use this")
# expected-error @below {{@unavailable and @deprecated cannot be used together}}
@deprecated("use something else")
def unavailable_and_deprecated():
...
# Order does not matter - still an error.
@deprecated("use something else")
# expected-error @below {{@unavailable and @deprecated cannot be used together}}
@unavailable("don't use this")
def deprecated_and_unavailable():
...
@unavailable("don't use this")
# expected-error @below {{@unavailable and @stable cannot be used together}}
@stable
def unavailable_and_stable():
...
# Order does not matter - still an error.
@stable
# expected-error @below {{@unavailable and @stable cannot be used together}}
@unavailable("don't use this")
def stable_and_unavailable():
...
# ===----------------------------------------------------------------------=== #
# Test: @unavailable(use=...) for methods
# ===----------------------------------------------------------------------=== #
def some_top_level_func():
pass
struct InstanceMethodRefTopLevel(Movable where False):
# Instance methods cannot reference top-level functions as replacements.
# expected-error @below {{cannot reference unknown value 'some_top_level_func'}}
@unavailable(use=some_top_level_func)
def instance_method(self):
...
# ===----------------------------------------------------------------------=== #
# Test: Cross-module unavailability errors
# ===----------------------------------------------------------------------=== #
from imported_module import unavailable_in_another_module
def use_unavailable_import():
# expected-error @below {{use of unavailable function in another module}}
unavailable_in_another_module()
# ===----------------------------------------------------------------------=== #
# Test: @unavailable method satisfying a trait requirement
#
# A struct cannot use an @unavailable method to satisfy a trait requirement.
# The error fires at the conformance declaration itself, which in turn prevents
# the type from being used through a generic constrained on the trait (e.g.
# `calls_trait_method[UnavailableTraitImpl]`): there is no way to reach a use
# site without first declaring the (rejected) conformance.
# ===----------------------------------------------------------------------=== #
trait Fooable:
def foo(self):
...
# expected-error @below {{unavailable trait method 'foo'}}
struct UnavailableTraitImpl(Fooable, Movable where False):
def __init__(out self):
pass
@unavailable("unavailable trait method 'foo'")
# expected-note @below {{'foo' declared here}}
def foo(self):
...
def calls_trait_method[T: Fooable](t: T):
# Inside the generic, `t.foo()` binds to the trait requirement `Fooable.foo`
# (which is available), so there is no error here. It is the conformance
# check above that rejects `UnavailableTraitImpl` as a `Fooable`.
t.foo()
def use_unavailable_via_trait():
var obj = UnavailableTraitImpl()
calls_trait_method(obj)
@@ -0,0 +1,45 @@
# ===----------------------------------------------------------------------=== #
# 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 the deprecated '__deinit__' destructor spelling is diagnosed with a
# warning and a fix-it to the canonical '__deinit__' spelling, while the
# canonical spelling itself is silent.
# RUN: %parse-mojo-isolated -verify-diagnostics %s
# Verify the fix-it text itself via the JSON diagnostic format.
# RUN: %parse-mojo-isolated --diagnostic-format json --use-mlir-diagnostics=false %s 2>&1 | FileCheck %s --check-prefix=FIXIT
# FIXIT: "diagnostic":{
# FIXIT-SAME: "fixIts":[{
# FIXIT-SAME: "text":"__deinit__"
struct UsesOldSpelling:
var x: Int
def __init__(out self):
self.x = 0
# expected-warning @+1 {{'__del__' is deprecated; use '__deinit__'}}
def __del__(deinit self):
pass
struct UsesNewSpelling:
var x: Int
def __init__(out self):
self.x = 0
def __deinit__(deinit self):
pass
@@ -0,0 +1,171 @@
# ===----------------------------------------------------------------------=== #
# 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
# Only `case name` and `case name(T, ...)` declare a case; every other spelling
# after `case` is rejected.
__enum Reserved:
# expected-note @+1 {{previous definition here}}
case a
# expected-error @+1 {{invalid redefinition of 'a'}}
case a
"""A doc string after a rejected case is still consumed."""
# expected-error @+1 {{labeled payloads in enum cases are not supported; use positional types, e.g. 'case C(T, U)'}}
case labeled(x: Int)
# expected-error @+1 {{labeled payloads in enum cases are not supported; use positional types, e.g. 'case C(T, U)'}}
case keyword(Int, y=Int)
# expected-error @+1 {{enum case must have the form 'case name' or 'case name(T, ...)'}}
case struct Nested:
pass
# expected-error @+1 {{enum case must have the form 'case name' or 'case name(T, ...)'}}
case typed: Int
"""A doc string after a rejected case is still consumed."""
# expected-error @+1 {{enum case must have the form 'case name' or 'case name(T, ...)'}}
case valued = 1
# expected-error @+1 {{enum case must have the form 'case name' or 'case name(T, ...)'}}
case several, names
# expected-error @+1 {{enum case must have the form 'case name' or 'case name(T, ...)'}}
case 1
# expected-error @+1 {{enum case must have the form 'case name' or 'case name(T, ...)'}}
case
# expected-error @+1 {{enum case must have the form 'case name' or 'case name(T, ...)'}}
case empty()
# expected-error @+1 {{enum case must have the form 'case name' or 'case name(T, ...)'}}
case trailing(Int) junk
# expected-error @+1 {{enum case must have the form 'case name' or 'case name(T, ...)'}}
case missing_comma(Int Int)
# expected-error @+2 {{'case' statement does not support decorators; remove the decorator}}
@always_inline
case decorated
# A rejected case still takes its name, so a later case with that name is a
# redefinition. A duplicate is rejected before its payload is resolved.
__enum Dropped:
# expected-error @+2 {{labeled payloads in enum cases are not supported; use positional types, e.g. 'case C(T, U)'}}
# expected-note @+1 {{previous definition here}}
case a(x: Int)
# expected-error @+1 {{invalid redefinition of 'a'}}
case a
# expected-error @+2 {{use of unknown declaration 'NotAType'}}
# expected-note @+1 {{previous definition here}}
case b(NotAType)
# expected-error @+1 {{invalid redefinition of 'b'}}
case b(AlsoNotAType)
struct Box[T: AnyType]:
pass
__enum Payloads:
# expected-error @+1 {{enum case payloads do not support trait types; 'AnyType' is a trait, use a concrete type or compile-time generic}}
case trait_payload(AnyType)
# expected-error @+1 {{use of unknown declaration 'NotAType'}}
case unknown_payload(NotAType)
# expected-error @+1 {{'Box[_]' is not concrete, use '[]' to bind missing parameters}}
case unbound_payload(Box)
__enum Stateful:
case a
# expected-error @+1 {{enums do not support 'var' fields; store state in a case payload}}
var x: Int
"""A doc string after a rejected field is still consumed."""
# A method body of only `...` is reserved in an enum.
__enum Bodies:
case a
def no_result(self):
# expected-error @+1 {{enum methods must have a body; '...' is reserved}}
...
def with_result(self) -> Int:
# expected-error @+1 {{enum methods must have a body; '...' is reserved}}
...
@staticmethod
def static_method():
"""A doc string does not count as a body."""
# expected-error @+1 {{enum methods must have a body; '...' is reserved}}
...
# expected-error @+1 {{enum methods must have a body; '...' is reserved}}
def one_line(self): ...
# expected-error @+1 {{enum methods must have a body; '...' is reserved}}
def with_semicolon(self): ...;
def two_ellipses(self):
# expected-error @+1 {{enum methods must have a body; '...' is reserved}}
...
...
def more_than_ellipsis(self):
...
pass
def outer(self):
def nested():
...
nested()
@unavailable("use 'a'")
def unavailable(self):
...
__extension Bodies:
def extension_method(self):
# expected-error @+1 {{enum methods must have a body; '...' is reserved}}
...
@unavailable("use 'a'")
def extension_unavailable(self):
...
# expected-error @+1 {{expected ':' in enum definition}}
__enum NoColon
case a
struct OuterStruct:
# expected-error @+1 {{nested enum not supported here}}
__enum Inner:
case a
trait OuterTrait:
# expected-error @+1 {{nested enum in a trait not supported here}}
__enum Inner:
case a
def outer_function():
# expected-error @+1 {{enum inside a function not supported here}}
__enum Inner:
case a
def comptime_enum():
# expected-error @+1 {{'comptime' cannot be used with '__enum'}}
comptime __enum = 1
# expected-error @+1 {{expected enum name}}
__enum
@@ -0,0 +1,157 @@
# ===----------------------------------------------------------------------=== #
# 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
# An enum holds the payload of its active case, so every payload type must
# support each conformance of the enum that copies, moves or destroys it.
__enum Copies(ImplicitlyCopyable):
case empty
# expected-error @+1 {{case 'list' has non-'ImplicitlyCopyable' payload type 'List[Int]'}}
case list(List[Int])
__enum Generic[T: AnyType]:
# expected-error @+1 {{case 'value' has non-'Deinitable' payload type 'T'}}
case value(Self.T)
# The storage of an enum has non-trivial copy, move and destruction. As for a
# struct whose header is rejected, the body is not resolved.
# expected-error @+1 {{enums cannot conform to 'TrivialRegisterPassable'}}
__enum Trivial(TrivialRegisterPassable):
case a
case b(NotAType)
# TODO(MOCO-5080): `NoneType` is `EnumLike`'s "no payload" marker, so a case
# cannot carry one; the rejection goes with the marker.
__enum NonePayload:
# expected-error @+1 {{enum case payload must not be 'NoneType'; a case without a payload is written 'case nothing'}}
case nothing(NoneType)
# An enum cannot hold itself by value.
__enum Chain:
case end
# expected-error @+1 {{case 'next' has recursive payload type 'Chain'}}
case next(Int, Self)
__enum Clash:
# expected-error @+1 {{enum case 'red' conflicts with a member of the same name}}
case red
# expected-error @+1 {{enum case 'blue' conflicts with a member of the same name}}
case blue(Int)
# expected-note @+1 {{member declared here}}
def red(self) -> Int:
return 1
# expected-note @+1 {{member declared here}}
comptime blue = 3
# expected-error @+1 {{'_get_enum_discriminant' is synthesized for enums and cannot be declared}}
def _get_enum_discriminant(self) -> Int:
return 0
# expected-error @+1 {{'_enum_elt_type_for_case' is synthesized for enums and cannot be declared}}
comptime _enum_elt_type_for_case[id: Int]: AnyType = Int
# An enum may declare that values other than its cases exist.
__enum Open:
case a
case b
comptime _enum_is_exhaustive = False
# A case generates a member, which must not collide with a member that is
# generated for every enum.
__enum ReservedByEnum:
case a
# expected-error @+1 {{invalid redefinition of '_get_enum_discriminant'}}
case _get_enum_discriminant(Int)
# expected-error @+1 {{invalid redefinition of '_enum_is_exhaustive'}}
case _enum_is_exhaustive
# expected-error @+1 {{invalid redefinition of '__enum_storage'}}
case __enum_storage
__enum ReservedByStruct(Copyable):
case a
# expected-error @+1 {{invalid redefinition of '__init__'}}
case __init__(Int)
# expected-error @+1 {{invalid redefinition of '__copy_ctor_is_trivial'}}
case __copy_ctor_is_trivial
# expected-error @+1 {{invalid redefinition of '__del__'}}
case __del__
# expected-error @+1 {{case '__eq__' must not use the name of a special method that takes 'self'; rename the case}}
case __eq__(Int)
# expected-error @+1 {{case '__ne__' must not use the name of a special method that takes 'self'; rename the case}}
case __ne__
# A `__` prefix is an ordinary case name, as it is an ordinary member name.
__enum Underscored:
case __first
case __second(Int)
# expected-error @+1 {{'@fieldwise_init' cannot be applied to an enum}}
@fieldwise_init
__enum Fieldwise:
case a
# `match` checks enum cases through the synthesized `EnumLike` conformance.
__enum Light:
case on
case off
case dimmed(Int)
def match_cases(light: Light) -> Int:
# expected-warning @+1 {{'match' is not exhaustive; missing case for 'off'}}
match light:
case .on:
return 1
case .dimmed(level):
return level
match light:
# expected-error @+1 {{'blinking' is not a case of 'Light'}}
case .blinking:
return 2
# expected-error @+1 {{enum case 'off' has no associated value}}
case .off(_):
return 3
case _:
return 4
# A copy constructor, move constructor or `__deinit__` written in the enum
# lifts the payload requirement of its own conformance only.
struct NoCopy(Movable):
var x: Int
def __init__(out self):
self.x = 0
__enum MovesByHand(Copyable):
# expected-error @+1 {{case 'held' has non-'Copyable' payload type 'NoCopy'}}
case held(NoCopy)
def __init__(out self, *, deinit move: Self):
self = Self.held(NoCopy())
@@ -0,0 +1,254 @@
# ===----------------------------------------------------------------------=== #
# 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 -o /dev/null
@fieldwise_init
struct MemoryType(ImplicitlyCopyable):
pass
def test_never_declared_fn():
# expected-error @+1 {{use of unknown declaration 'never_declared_fn'}}
never_declared_fn()
def implicit_var_decl(a: Int):
# expected-error @+1 {{implicit declaration of 'c' is not allowed; add 'var' to declare a new name}}
c = a
struct BadMethod(Movable where False):
# expected-error @+1 {{'__add__' requires 2 operands}}
def __add__(self):
pass
# expected-error @+1 {{'__sub__' must be a method, not a global function}}
def __sub__(self: Int, a: Int):
pass
def missing_colon() # expected-error {{expected ':' in function definition}}
# Don't get confused by comments or blank lines!
var x = 1
# Missing colon after def definition complains about function effects
# https://github.com/modularml/modular/issues/23359
# expected-error @+1 {{missing ':' at end of function signature}}
def missing_colon_2()
test_never_declared_fn()
# expected-error @+1 {{function effect 'thin' must only be used on function types}}
def invalid_thin_effect() thin:
pass
# expected-error @+1 {{function effect 'thin' must only be used on function types}}
def invalid_thin_before_abi() thin abi("C"):
pass
# expected-error @+1 {{function effect 'thin' must only be used on function types}}
def invalid_abi_before_thin() abi("C") thin:
pass
# expected-error @below {{expected argument name}}
def missing_argument_name(*: Int): pass
# expected-error @below {{expected parameter name}}
def missing_parameter_name[: Int](): pass
# expected-error @+1 {{use of unknown declaration 'InvalidType'}}
def test_unknown_arg_type(a: InvalidType) raises:
_ = a.value # Should not produce a follow-on error.
return
# expected-error @+1 {{cannot have two '*' markers in the same argument list}}
def two_stars(a: Int, *, *, b: Int):
pass
# expected-error @+1 {{cannot have two '/' markers in the same argument list}}
def two_slashes(a: Int, /, /, b: Int):
pass
# expected-error @+1 {{cannot specify '/' marker after '*' marker}}
def slash_after_start(a: Int, *, /, b: Int):
pass
# expected-error @+1 {{'/' marker cannot be used at the start of the argument list}}
def leading_slash(/, a: Int):
pass
# expected-error @+1 {{'*' marker is not allowed at end of argument list}}
def trailing_star(a: Int, *):
pass
# # expected-error @+1 {{cannot have two '*' markers in the same argument list}}
def two_variadics(*a: Int, *b: Int):
pass
# expected-error @+1 {{cannot have two '*' markers in the same argument list}}
def two_variadic_packs[*Ts: TrivialRegisterPassable](*a: *Ts, *b: *Ts):
pass
# expected-error @+2 {{parametric functions must not be used as arguments; pass as a parameter instead}}
# expected-note @+1 {{alternatively, bind its type parameters to create a concrete function}}
def foo(x: def[a: Int] () thin -> None):
pass
# Member-alias sugar must not bypass the non-singleton parameter check.
struct ParametricFnType:
comptime type = def[a: Int] () thin -> None
# expected-error @+2 {{parametric functions must not be used as arguments; pass as a parameter instead}}
# expected-note @+1 {{alternatively, bind its type parameters to create a concrete function}}
def parametric_fn_alias_as_arg(func: ParametricFnType.type):
pass
# Bare `ref` invents a non-singleton Bool mutability parameter; only unbound
# origin / other singleton parameters are allowed on runtime function arguments.
# expected-error @+2 {{parametric functions must not be used as arguments; pass as a parameter instead}}
# expected-note @+1 {{alternatively, bind its type parameters to create a concrete function}}
def unbound_ref_fn_as_arg(func: def(ref arg: Int) thin -> None):
pass
# expected-error @below {{non-owned variadic keyword arguments are not supported yet}}
def borrowed_kwargs(imm **kwargs: Int):
pass
# expected-error @below {{variadic keyword arguments only support the 'var' convention; add 'var' before '**'}}
def bare_kwargs(**kwargs: Int):
pass
def bare_kwargs_fn_type(
# expected-error @below {{variadic keyword arguments only support the 'var' convention; add 'var' before '**'}}
f: def(**kwargs: Int) -> None,
):
pass
# The parser recovers from a missing 'var' as if it were written, so later
# arguments are still checked.
# expected-error @below {{variadic keyword arguments only support the 'var' convention; add 'var' before '**'}}
# expected-error @below {{'**' marker must be at end of argument list}}
def bare_kwargs_not_last(**kwargs: Int, b: Int):
pass
# expected-error @below {{'//' marker cannot be used at the start of the parameter list}}
def invalid_inferred[//, x: Int]():
pass
# expected-error @below {{cannot specify '//' marker after '*' marker in parameter list}}
def invalid_inferred_kw_only[*, x: Int, //, y: Int]():
pass
# expected-error @below {{'//' is reserved for parameter lists; it marks the end of 'infer-only' parameter listings}}
def invalid_inferred_argument(x: Int, //):
pass
struct NonCopyable(Movable where False):
def __init__(out self):
pass
def defTests() raises -> None:
comptime abc = 1
# MOCO-83: [mojo][Bug] def methods can't shadow names via assignment
# expected-error @+1 {{expression must be mutable in assignment}}
abc = 4
# expected-error @+1 {{value of type 'IntLiteral[4]' doesn't have a memory origin in origin specifier}}
def ref_result_invalid1() -> ref [4] MemoryType:
pass
def ref_result_invalid2(mut a: MemoryType) -> ref [a] Int:
# expected-error @+1 {{value of type 'Int' doesn't have a memory origin in return value}}
return 4
def ref_result_invalid3(mut a: MemoryType, mut b: MemoryType)
-> ref [a] MemoryType:
# expected-error @+1 {{cannot return reference with incompatible origin: 'origin_of(b)' vs 'origin_of(a)'}}
return b
def ref_result_invalid4(mut a: MemoryType, b: Int) -> ref [a] MemoryType:
# expected-error @+1 {{cannot implicitly convert 'Int' value to 'MemoryType'}}
return b
# expected-error @+1 {{cannot return 'a's origin, because it might expand to a RegisterPassable type}}
def ref_result_invalid5[T: AnyType](a: T) -> ref [a] T:
return a
# expected-error @+1 {{cannot return 'b's origin, because it has RegisterPassable type 'Int'}}
def ref_result_invalid6(mut a: MemoryType, mut b: Int) -> ref [b] Int:
pass
# expected-error @+1 {{'ref' result requires an origin specifier}}
def ref_result_invalid7() -> ref MemoryType:
pass
# expected-error @+1 {{value of type 'Int' doesn't have a memory origin in origin specifier}}
def ref_result_invalid8(a: Int) -> ref [a] MemoryType:
pass
# expected-error @+1 {{cannot infer origin for a function result}}
def ref_result_invalid9() -> ref [_] MemoryType:
pass
# expected-error @+1 {{origin in origin specifier must outlive the expression naming it}}
def ref_result_invalid10() -> ref [String("lit")] MemoryType:
pass
def valid_ref_result(x: MemoryType) -> ref [x] MemoryType: return x
def ref_invalid():
var a = MemoryType()
# expected-error @+1 {{expression must be mutable in assignment}}
valid_ref_result(a) = MemoryType()
def return_ref_type_error(a: def (x: MemoryType) thin -> ref [x] MemoryType):
# expected-error @+1 {{cannot implicitly convert 'def(x: MemoryType) thin -> ref[*[0,0]] MemoryType' value to 'Int'}}
var b: Int = a
struct SBValue(RegisterPassable):
pass
# expected-error @below {{TODO: read-only non-trivial register-passable arguments are not yet supported in async functions}}
__async def invalid_sb_value(value: SBValue):
pass
# expected-error @below {{TODO: read-only non-trivial register-passable arguments are not yet supported in async functions}}
__async def invalid_sb_value_variadic(*value: SBValue):
pass
__async def borrowed_generic_arg[T: AnyType](value: T):
pass
def valid_sbvalue_borrow(value: SBValue):
_ = borrowed_generic_arg(value)
# expected-error @+1 {{address space must be specified once; remove duplicate address space specifications}}
def bad_ref_as[a: AddressSpace](ref [a, a] x: Int):
pass
# expected-error @+1 {{origin in origin specifier must outlive the expression naming it}}
def bad_ref_temporary(ref [String("lit")] x: Int):
pass
struct HasOwnedOverloadedMethod(Movable where False):
def method(var self) -> Int: pass
def method(self) -> String: pass
def testOverloadedMethod():
var x : HasOwnedOverloadedMethod
_: Int = x.method() # expected-error {{cannot implicitly convert 'String' value to 'Int'}}
_: String = x.method()
_: Int = x^.method()
_: String = x^.method() # expected-error {{cannot implicitly convert 'Int' value to 'String'}}
@@ -0,0 +1,63 @@
# ===----------------------------------------------------------------------=== #
# 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.
# ===----------------------------------------------------------------------=== #
# A function type's trailing `where` clauses are an obligation, not part of its
# representation, so a constrained function is not interchangeable with an
# unconstrained one of the same shape. Dropping the clause has to be refused
# unless it can be proven: the value would be rebound to a type that no longer
# mentions the obligation, and a later call through it would never recheck it.
# RUN: %parse-mojo-isolated -verify-diagnostics %s
trait Marker:
pass
def marked_impl[T: AnyType](x: Int) where conforms_to(T, Marker):
pass
# expected-note @below {{function declared here}}
def takes_unmarked[F: def[T: AnyType](Int) thin -> None]():
pass
# Nothing in this scope proves `conforms_to(T, Marker)` for an arbitrary `T`, so
# the constraint cannot be shed to reach the unconstrained parameter type.
def shed_without_evidence():
# expected-error @below {{parameter 'F' has 'def[T: AnyType](Int) thin -> None' type, but value has type 'def marked_impl[T: AnyType](x: Int) thin -> None where conforms_to(T, Marker)'}}
takes_unmarked[marked_impl]()
# The same refusal applies to non-function generator types: a `where` clause on
# a `comptime` generator alias is a body constraint, and shedding it to reach an
# unconstrained generator type is refused unless this scope proves it.
comptime plain_gen[U: AnyType] = U
comptime marked_gen[U: AnyType] where conforms_to(U, Marker) = U
comptime PlainGenType = type_of(plain_gen)
# expected-note @+1 {{function declared here}}
def takes_plain_gen[F: PlainGenType]():
pass
def shed_nonfn_without_evidence():
# expected-error @+2 {{parameter 'F' has 'PlainGenType' type, but value has type '__generator_type[U: AnyType] AnyType where conforms_to(U, Marker)'}}
# expected-note @+1 {{'PlainGenType' is aka '__generator_type[U: AnyType] AnyType'}}
takes_plain_gen[marked_gen]()
@@ -0,0 +1,55 @@
# ===----------------------------------------------------------------------=== #
# 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 violated_at_explicit_bind[
# expected-note @below {{constraint declared here evaluated to False, expected '(w > Int(0))': width must be positive}}
F: def[w: Int](Int) thin -> None where (w > 0, "width must be positive")
]():
# expected-error @below {{violated constraint}}
F[0](0)
# The constraint rides on the returned function type, so it is checked at the
# indirect call rather than at the call to the returning function.
# expected-note @below {{constraint declared here evaluated to False, expected '(Int(0) > Int(0))'}}
def violated_through_returned_value[n: Int]() -> def() thin -> None where n > 0:
def inner():
pass
return inner
def call_returned_value():
# expected-error @below {{invalid indirect call: violated constraint}}
violated_through_returned_value[0]()()
# A `where` clause inside a function type's parameter list points at the
# trailing form.
def inline_where_in_fn_type[
# expected-error @below {{'where' clauses inside parameter lists are no longer supported}}
# expected-note @below {{use a trailing 'where' clause after the result type of a 'thin' function type instead}}
f: def[a: Int where a > 0]() thin -> None
]():
pass
# A `where` clause in a function type's argument list constrains nothing.
def where_in_fn_type_args[
# expected-error @below {{'where' clauses must be used with parameters and cannot be used with arguments}}
f: def(x: Int where x > 0) thin -> None
]():
pass
@@ -0,0 +1,82 @@
# ===----------------------------------------------------------------------=== #
# 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.
# ===----------------------------------------------------------------------=== #
# 'imm' is the new spelling of the immutable-borrow argument and
# closure-capture convention; 'read' is a removed synonym that warns with a
# fixit (fixit positions are covered by imm_convention_fixit.mojo, IR
# equivalence by imm_convention_ir.mojo).
# RUN: %parse-mojo-isolated -split-input-file -verify-diagnostics %s
# 'imm' parses without diagnostics in argument and capture position.
def imm_arg(imm x: Int) -> Int:
return x
def imm_capture() -> Int:
var base = 0
def closure() {imm base} -> Int:
return base
return closure()
# // -----
# 'read' still parses but is deprecated in argument position...
# expected-error @below {{'read' was removed; use 'imm'}}
def read_arg(read x: Int) -> Int:
return x
# // -----
# ...and in capture position.
def read_capture() -> Int:
var base = 0
# expected-error @below {{'read' was removed; use 'imm'}}
def closure() {read base} -> Int:
return base
return closure()
# // -----
# Like 'read', 'imm' is claimed by convention parsing in argument lists, so it
# cannot be an argument name.
# expected-error @below {{expected argument name}}
def imm_as_arg_name(imm: Int):
pass
# // -----
# Parameter lists don't take conventions, so 'imm' remains a valid parameter
# name there, and it is still a soft keyword usable as a local variable name.
def param_named_imm[imm: Int]() -> Int:
var imm2 = imm
return imm2
def local_named_imm() -> Int:
var imm = 5
return imm
@@ -0,0 +1,393 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
# Tests for the error on an implicitly declared variable, and for the binding
# forms that must stay silent because they already spell out how they bind.
# Related to MOCO-3182.
# RUN: %parse-mojo-isolated %s -verify-diagnostics -o /dev/null
struct ExampleCM(ImplicitlyCopyable):
def __enter__(self) -> Int:
return 1
def __exit__(self):
pass
def one() -> Int:
return 1
def truthy() -> Bool:
return True
def use(x: Int):
pass
def use_bool(x: Bool):
pass
def simple():
# expected-error @+1 {{implicit declaration of 'x' is not allowed; add 'var' to declare a new name}}
x = 1
use(x)
def annotated():
# expected-error @+1 {{implicit declaration of 'x' is not allowed; add 'var' to declare a new name}}
x: Int = 5
use(x)
# An annotation with no initializer declares just as much as an assignment does.
def annotated_no_initializer():
# expected-error @+1 {{implicit declaration of 'x' is not allowed; add 'var' to declare a new name}}
x: Int
x = 5
use(x)
# Only the first assignment is diagnosed; the name is then registered, so later
# assignments and uses resolve against it.
def reassigned():
# expected-error @+1 {{implicit declaration of 'x' is not allowed; add 'var' to declare a new name}}
x = 1
x = 2
use(x)
# A single 'var' covers a whole tuple target. Emission stops after the first
# unresolved element, so only that name is diagnosed and only it is registered;
# later elements stay unknown.
def tuple_target():
# expected-error @+1 {{implicit declaration of 'a' is not allowed; add 'var' to declare a new name}}
a, b = Tuple(1, 2)
use(a)
# expected-error @+1 {{use of unknown declaration 'b'}}
use(b)
# Only the fresh element is diagnosed when the target mixes declared and fresh names.
def tuple_mixed():
var a = 0
# expected-error @+1 {{implicit declaration of 'b' is not allowed; add 'var' to declare a new name}}
a, b = Tuple(1, 2)
use(a)
use(b)
# With no binder anywhere in the target, emission still stops at the first
# unresolved name.
def nested_tuple_target_no_binder():
# expected-error @+1 {{implicit declaration of 'a' is not allowed; add 'var' to declare a new name}}
(a, b), c = Tuple(Tuple(1, 2), 3)
use(a)
# expected-error @+1 {{use of unknown declaration 'b'}}
use(b)
# expected-error @+1 {{use of unknown declaration 'c'}}
use(c)
def nested_tuple_target_no_binder_migrated():
var (a, b), c = Tuple(Tuple(1, 2), 3)
use(a)
use(b)
use(c)
# TODO(MOCO-4520): the migrated form of the case above belongs here, spelling
# the two names as `var a: Int` / `var b: Int`. It is omitted because an inner
# tuple that fully resolves, beside a sibling that does not, strands an owning
# `RCRef<TupleDLValue>` in the parser's persistent arena, and LeakSanitizer
# reports it. The unmigrated form above is unaffected: its names are fresh, so
# the inner tuple never resolves and no `TupleDLValue` is formed.
# TODO(MOCO-4520): the same spelling is missing for the tuple chain below;
# omitted for the same arena leak.
# Each target of a chain declares, and 'var' on each is a valid spelling.
def chained():
# expected-error @+2 {{implicit declaration of 'a' is not allowed; add 'var' to declare a new name}}
# expected-error @+1 {{implicit declaration of 'b' is not allowed; add 'var' to declare a new name}}
a = b = 1
use(a)
use(b)
def chained_migrated():
var a = var b = 1
use(a)
use(b)
# A chain of tuple targets diagnoses the first unresolved name in each target.
def chain_tuple():
# expected-error @+2 {{implicit declaration of 'a' is not allowed; add 'var' to declare a new name}}
# expected-error @+1 {{implicit declaration of 'c' is not allowed; add 'var' to declare a new name}}
a, b = c, d = Tuple(1, 2)
use(a)
# expected-error @+1 {{use of unknown declaration 'b'}}
use(b)
use(c)
# expected-error @+1 {{use of unknown declaration 'd'}}
use(d)
def chain_tuple_migrated():
var a, b = var c, d = Tuple(1, 2)
use(a)
use(b)
use(c)
use(d)
# A walrus target must already be an LValue, so it never reaches the
# implicit-declaration path at all.
def walrus_condition():
# expected-error @+1 {{use of unknown declaration 'x'}}
if x := truthy():
use_bool(x)
# Hoisting the declaration leaves the walrus assigning it rather than
# introducing one, so nothing is reported.
def walrus_condition_hoisted():
var x: Bool
if x := truthy():
use_bool(x)
use_bool(x)
def walrus_in_call_hoisted():
var x: Int
use(x := 1)
# One 'var' covers a whole tuple target, but a walrus target takes none, so each
# element hoists instead of naming the target.
def walrus_tuple_target_hoisted():
var a: Int
var b: Int
use(((a, b) := Tuple(1, 2))[0])
use(a)
use(b)
# Each target of a mixed chain answers for itself, so the plain one keeps the
# name message and its fixit. The other order is not a shape to pin:
# `a := b = 1` does not parse.
def walrus_in_chain():
var c: Int
var d: Int
d = c := 5
use(c)
use(d)
# ===----------------------------------------------------------------------=== #
# Sites inside a nested block still reject implicit declarations the same way.
# ===----------------------------------------------------------------------=== #
def nested_if(c: Bool):
# expected-error @+2 {{implicit declaration of 'x' is not allowed; add 'var' to declare a new name}}
if c:
x = 1
use(1)
def nested_loop(items: List[Int]):
# expected-error @+2 {{implicit declaration of 'x' is not allowed; add 'var' to declare a new name}}
for i in items:
x = i
use(1)
def nested_with(cm: ExampleCM):
# expected-error @+2 {{implicit declaration of 'x' is not allowed; add 'var' to declare a new name}}
with cm as v:
x = v
use(1)
# The first arm is diagnosed and registers the name, so the second arm and the
# use after the statement resolve against it.
def nested_both_arms(c: Bool):
# expected-error @+2 {{implicit declaration of 'x' is not allowed; add 'var' to declare a new name}}
if c:
x = 1
else:
x = 2
use(x)
# Explicit declaration before the nested statement.
def nested_hoisted(c: Bool):
var x: Int
if c:
x = 1
else:
x = 2
use(x)
# Nested tuple targets get the same message; emission stops at the first
# unresolved name.
def nested_tuple_target(c: Bool):
# expected-error @+2 {{implicit declaration of 'a' is not allowed; add 'var' to declare a new name}}
if c:
a, b = Tuple(1, 2)
use(1)
def nested_while(c: Bool):
# expected-error @+2 {{implicit declaration of 'x' is not allowed; add 'var' to declare a new name}}
while c:
x = 1
use(1)
def nested_comptime_if():
# expected-error @+2 {{implicit declaration of 'x' is not allowed; add 'var' to declare a new name}}
comptime if True:
x = 1
use(1)
def nested_for_else(items: List[Int]):
for i in items:
use(i)
# expected-error @+2 {{implicit declaration of 'x' is not allowed; add 'var' to declare a new name}}
else:
x = 1
use(1)
# A nested 'def' has its own function body; implicit decls there are rejected
# the same way.
def nested_def_body():
def inner():
# expected-error @+1 {{implicit declaration of 'x' is not allowed; add 'var' to declare a new name}}
x = 1
use(x)
inner()
# Registration is on the enclosing function, so a nested 'def' resolves the name
# through parent scope rather than reporting it again.
def nested_def_reads_outer():
# expected-error @+1 {{implicit declaration of 'x' is not allowed; add 'var' to declare a new name}}
x = 1
def inner():
use(x)
inner()
# A capture list resolves through a lookup of its own, so it is pinned too.
def closure_reads_outer():
# expected-error @+1 {{implicit declaration of 'x' is not allowed; add 'var' to declare a new name}}
x = 1
def cl(z: Int) {imm x} -> Int:
return x + z
use(cl(1))
# A lambda's capture list reaches that lookup by a different path.
def lambda_capture_reads_outer():
# expected-error @+1 {{implicit declaration of 'x' is not allowed; add 'var' to declare a new name}}
x = 1
use((lambda (z: Int) {imm x} -> Int: x + z)(1))
# Registration is per name, so a later 'var' of that name is a redefinition and
# is reported as one.
def redeclared_with_var():
# expected-error @+2 {{implicit declaration of 'x' is not allowed; add 'var' to declare a new name}}
# expected-note @+1 {{previous definition here}}
x = 1
# expected-error @+1 {{invalid redefinition of 'x'}}
var x = 2
use(x)
# ===----------------------------------------------------------------------=== #
# A short-circuit operand, a conditional-expression arm and a comprehension body
# are reachable only by a walrus, and each also gets a block of its own, so both
# rules point the same way there.
# ===----------------------------------------------------------------------=== #
def comprehension_walrus_hoisted(items: List[Int]):
var x: Int
var doubled = [(x := i) for i in items]
use(doubled[0])
# ===----------------------------------------------------------------------=== #
# Forms that already spell out their binding, and must stay silent.
# ===----------------------------------------------------------------------=== #
def explicit_var():
var x = 1
use(x)
def for_target(items: List[Int]):
for i in items:
use(i)
def for_var_target(items: List[Int]):
for var i in items:
use(i)
def with_target(cm: ExampleCM):
with cm as x:
use(x)
def except_target() raises:
try:
use(one())
except err:
pass
def comprehension_target(items: List[Int]):
var doubled = [i * 2 for i in items]
use(doubled[0])
def discard():
_ = one()
struct StructWithField(ImplicitlyCopyable):
# expected-note @+1 {{'f' declared here}}
var f: Int
def set_it(self):
# expected-error @+2 {{implicit declaration of 'f' is not allowed; add 'var' to declare a new name}}
# expected-note @+1 {{'f' is also a struct field; did you mean 'self.'?}}
f = 1
@@ -0,0 +1,20 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
struct _Impl(Movable where False):
pass
# @expected-note @below {{'Foo' declared here}}
comptime Foo = _Impl
@@ -0,0 +1,20 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
struct _Impl(Movable where False):
pass
# @expected-note @below {{'Foo' also declared here}}
comptime Foo = _Impl
@@ -0,0 +1,18 @@
# ===----------------------------------------------------------------------=== #
# 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.
# ===----------------------------------------------------------------------=== #
# @expected-note @below {{'Foo' declared here}}
# @expected-note @below {{function declared here}}
def Foo():
pass
@@ -0,0 +1,17 @@
# ===----------------------------------------------------------------------=== #
# 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.
# ===----------------------------------------------------------------------=== #
# @expected-note @below {{'Foo' also declared here}}
def Foo(x: Bool):
pass
@@ -0,0 +1,17 @@
# ===----------------------------------------------------------------------=== #
# 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.
# ===----------------------------------------------------------------------=== #
# @expected-note @below {{'Foo' also declared here}}
def Foo():
pass
@@ -0,0 +1,17 @@
# ===----------------------------------------------------------------------=== #
# 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.
# ===----------------------------------------------------------------------=== #
# @expected-note @below {{'Foo' declared here}}
def Foo():
pass
@@ -0,0 +1,22 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
struct DTypePointer(Movable where False):
pass
@deprecated("use of deprecated struct 'DeprecatedInAnotherModule'")
# expected-note @below {{'DeprecatedInAnotherModule' declared here}}
struct DeprecatedInAnotherModule(Movable where False):
pass
@@ -0,0 +1,15 @@
# ===----------------------------------------------------------------------=== #
# 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.
# ===----------------------------------------------------------------------=== #
# @expected-note @below {{'Foo' declared here}}
comptime Foo = __mlir_type.i1
@@ -0,0 +1,15 @@
# ===----------------------------------------------------------------------=== #
# 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.
# ===----------------------------------------------------------------------=== #
# @expected-note @below {{'Foo' also declared here}}
comptime Foo = __mlir_type.i1
@@ -0,0 +1,17 @@
# ===----------------------------------------------------------------------=== #
# 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.
# ===----------------------------------------------------------------------=== #
# @expected-note @below {{'Foo' declared here}}
struct Foo(Movable where False):
pass
@@ -0,0 +1,17 @@
# ===----------------------------------------------------------------------=== #
# 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.
# ===----------------------------------------------------------------------=== #
# @expected-note @below {{'Foo' also declared here}}
struct Foo(Movable where False):
pass
@@ -0,0 +1,17 @@
# ===----------------------------------------------------------------------=== #
# 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.
# ===----------------------------------------------------------------------=== #
# @expected-note @below {{'Foo' declared here}}
struct Foo(Movable where False):
pass
@@ -0,0 +1,17 @@
# ===----------------------------------------------------------------------=== #
# 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.
# ===----------------------------------------------------------------------=== #
# @expected-note @below {{'Foo' also declared here}}
struct Foo(Movable where False):
pass
@@ -0,0 +1,17 @@
# ===----------------------------------------------------------------------=== #
# 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.
# ===----------------------------------------------------------------------=== #
# @expected-note @below {{also referencing struct 'PlainStruct' declared here}}
struct PlainStruct:
pass
@@ -0,0 +1,280 @@
# ===----------------------------------------------------------------------=== #
# 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
# expected-error @+1 {{'_' cannot be used as a function name in this context}}
def _():
pass
# expected-error @+1 {{'and' cannot be used as a function name in this context}}
def and():
pass
# expected-error @+1 {{'as' cannot be used as a function name in this context}}
def as():
pass
# expected-error @+1 {{'assert' cannot be used as a function name in this context}}
def assert():
pass
# expected-error @+1 {{'break' cannot be used as a function name in this context}}
def break():
pass
# expected-error @+1 {{'case' cannot be used as a function name in this context}}
def case():
pass
# expected-error @+1 {{'class' cannot be used as a function name in this context}}
def class():
pass
# expected-error @+1 {{'comptime' cannot be used as a function name in this context}}
def comptime():
pass
# expected-error @+1 {{'continue' cannot be used as a function name in this context}}
def continue():
pass
# expected-error @+1 {{'def' cannot be used as a function name in this context}}
def def():
pass
# expected-error @+1 {{'del' cannot be used as a function name in this context}}
def del():
pass
# expected-error @+1 {{'elif' cannot be used as a function name in this context}}
def elif():
pass
# expected-error @+1 {{'else' cannot be used as a function name in this context}}
def else():
pass
# expected-error @+1 {{'except' cannot be used as a function name in this context}}
def except():
pass
# expected-error @+1 {{'False' cannot be used as a function name in this context}}
def False():
pass
# expected-error @+1 {{'finally' cannot be used as a function name in this context}}
def finally():
pass
# expected-error @+1 {{'for' cannot be used as a function name in this context}}
def for():
pass
# expected-error @+1 {{'from' cannot be used as a function name in this context}}
def from():
pass
# expected-error @+1 {{'global' cannot be used as a function name in this context}}
def global():
pass
# expected-error @+1 {{'if' cannot be used as a function name in this context}}
def if():
pass
# expected-error @+1 {{'import' cannot be used as a function name in this context}}
def import():
pass
# expected-error @+1 {{'in' cannot be used as a function name in this context}}
def in():
pass
# expected-error @+1 {{'is' cannot be used as a function name in this context}}
def is():
pass
# expected-error @+1 {{'lambda' cannot be used as a function name in this context}}
def lambda():
pass
# expected-error @+1 {{'match' cannot be used as a function name in this context}}
def match():
pass
# expected-error @+1 {{'None' cannot be used as a function name in this context}}
def None():
pass
# expected-error @+1 {{'nonlocal' cannot be used as a function name in this context}}
def nonlocal():
pass
# expected-error @+1 {{'not' cannot be used as a function name in this context}}
def not():
pass
# expected-error @+1 {{'or' cannot be used as a function name in this context}}
def or():
pass
# expected-error @+1 {{'pass' cannot be used as a function name in this context}}
def pass():
pass
# expected-error @+1 {{'raise' cannot be used as a function name in this context}}
def raise():
pass
# expected-error @+1 {{'ref' cannot be used as a function name in this context}}
def ref():
pass
# expected-error @+1 {{'return' cannot be used as a function name in this context}}
def return():
pass
# expected-error @+1 {{'Self' cannot be used as a function name in this context}}
def Self():
pass
# expected-error @+1 {{'struct' cannot be used as a function name in this context}}
def struct():
pass
# expected-error @+1 {{'trait' cannot be used as a function name in this context}}
def trait():
pass
# expected-error @+1 {{'__async' cannot be used as a function name in this context}}
def __async():
pass
# expected-error @+1 {{'__await' cannot be used as a function name in this context}}
def __await():
pass
# expected-error @+1 {{'async' cannot be used as a function name in this context}}
def async():
pass
# expected-error @+1 {{'await' cannot be used as a function name in this context}}
def await():
pass
# expected-error @+1 {{'__extension' cannot be used as a function name in this context}}
def __extension():
pass
# expected-error @+1 {{'True' cannot be used as a function name in this context}}
def True():
pass
# expected-error @+1 {{'try' cannot be used as a function name in this context}}
def try():
pass
# expected-error @+1 {{'var' cannot be used as a function name in this context}}
def var():
pass
# expected-error @+1 {{'while' cannot be used as a function name in this context}}
def while():
pass
# expected-error @+1 {{'with' cannot be used as a function name in this context}}
def with():
pass
# expected-error @+1 {{'yield' cannot be used as a function name in this context}}
def yield():
pass
# expected-error @+1 {{'__mlir_region' cannot be used as a function name in this context}}
def __mlir_region():
pass
# expected-error @+1 {{'__get_address_as_uninit_lvalue' cannot be used as a function name in this context}}
def __get_address_as_uninit_lvalue():
pass
# expected-error @+1 {{'__get_mvalue_as_litref' cannot be used as a function name in this context}}
def __get_mvalue_as_litref():
pass
# expected-error @+1 {{'__get_litref_as_mvalue' cannot be used as a function name in this context}}
def __get_litref_as_mvalue():
pass
# expected-error @+1 {{'__get_address_as_owned_value' cannot be used as a function name in this context}}
def __get_address_as_owned_value():
pass
# expected-error @+1 {{'origin_of' cannot be used as a function name in this context}}
def origin_of():
pass
# expected-error @+1 {{'type_of' cannot be used as a function name in this context}}
def type_of():
pass
# expected-error @+1 {{'conforms_to' cannot be used as a function name in this context}}
def conforms_to():
pass
# expected-error @+1 {{'__functions_in_module' cannot be used as a function name in this context}}
def __functions_in_module():
pass
# expected-error @+1 {{'__get_current_function_name' cannot be used as a function name in this context}}
def __get_current_function_name():
pass
# expected-error @+1 {{'__struct_field_ref' cannot be used as a function name in this context}}
def __struct_field_ref():
pass
# expected-error @+1 {{'__is_run_in_comptime_interpreter' cannot be used as a function name in this context}}
def __is_run_in_comptime_interpreter():
pass
# expected-error @+1 {{'__match' cannot be used as a function name in this context}}
def __match():
pass
# expected-error @+1 {{'__enum' cannot be used as a function name in this context}}
def __enum():
pass
# Nested free functions are rejected too.
def outer():
# expected-error @+1 {{'match' cannot be used as a function name in this context}}
def match():
pass
# Keyword method names are allowed (reached via `.name()`).
struct Bar:
def __init__(out self):
pass
def match(self):
pass
def class(self):
pass
def yield(self):
pass
@@ -0,0 +1,114 @@
# ===----------------------------------------------------------------------=== #
# 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
trait SomeTrait:
pass
struct StructWithField(Movable where False):
var field: __mlir_type.index
# Issue #6879: Qualified lookup is looking up names wrong
def unqualified_name_lookup(a: StructWithField):
# expected-error @+1 {{StructWithField' value has no attribute 'badPropertyError'}}
a.badPropertyError
# expected-error @+1 {{StructWithField' value has no attribute 'badPropertyError'}}
StructWithField.badPropertyError
# expected-error @+1 {{'SomeTrait' value has no attribute 'value'}}
SomeTrait.value
# expected-error @+1 {{cannot access instance field 'field' without an instance of 'StructWithField'}}
StructWithField.field
struct DirectInstanceReference(Movable where False):
comptime my_alias: Int = 8
var value: Int
def fxn(self):
# expected-error @+1 {{cannot access instance field 'value' directly; did you mean 'self.'?}}
var xx = value
# expected-error @+1 {{cannot access comptime 'my_alias' directly; did you mean 'Self.'?}}
_ = my_alias
@staticmethod
def stat():
# expected-error @+1 {{cannot access method 'fxn' directly; did you mean 'Self.'?}}
_ = fxn
def direct_ref(self):
# expected-error @+1 {{cannot access method 'fxn' directly; did you mean 'self.'?}}
fxn(self)
# expected-error @+1 {{cannot access method 'stat' directly; did you mean 'Self.'?}}
stat()
def field_indexes(a: DirectInstanceReference):
# expected-error @+1 {{'DirectInstanceReference' value has no attribute 'badField'}}
a.badField = 42
trait DirectTraitMemberReference:
comptime my_alias: Int
def fxn(self):
# expected-error @+1 {{cannot access comptime 'my_alias' directly; did you mean 'Self.'?}}
_ = my_alias
@staticmethod
def stat():
# expected-error @+1 {{cannot access method 'fxn' directly; did you mean 'Self.'?}}
_ = fxn
def direct_ref(self):
# expected-error @+1 {{cannot access method 'fxn' directly; did you mean 'Self.'?}}
fxn(self)
# expected-error @+1 {{cannot access method 'stat' directly; did you mean 'Self.'?}}
stat()
struct StructWithParam[a: Int](Movable where False):
pass
@fieldwise_init
struct UnqualifiedStructParameterAccess[
my_param: Int, # expected-note {{parameter 'my_param' declared here}}
other_param: Int,
struct_param: StructWithParam[my_param], # this should be okay
](Movable where False):
# expected-error @+1 {{unqualified access to struct parameter 'my_param'; use 'Self.my_param' instead}}
comptime my_alias = my_param
def bar(self) -> Int:
def nested_fn() capturing:
# expected-error @+1 {{unqualified access to struct parameter 'my_param'; use 'Self.my_param' instead}}
comptime my_different_alias = my_param
def shadowing_nested_fn[my_param: Int]() capturing:
# There should be no warning here because the comptime is shadowed.
comptime my_different_alias = my_param
nested_fn()
shadowing_nested_fn[4]()
# expected-error @+1 {{unqualified access to struct parameter 'my_param'; use 'Self.my_param' instead}}
comptime my_other_alias = my_param
# expected-error @+1 {{unqualified access to struct parameter 'my_param'; use 'Self.my_param' instead}}
return my_param
@@ -0,0 +1,208 @@
# ===----------------------------------------------------------------------=== #
# 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.
# ===----------------------------------------------------------------------=== #
# Errors for the `not Trait` conformance-list entry (see `not_conformance.mojo`
# for the accepted forms).
#
# A trait opted out with `not` and then mentioned again in the same list is
# diagnosed as a repeated trait, not as disagreeing constraints: the user wrote
# no constraint to reconcile, and one of the two entries is dead either way.
# The transitive case needs resolved trait symbols to see that a derived trait
# drags its ancestor in, so it is caught alongside the ordinary
# derived-implies-ancestor check rather than during parsing.
# RUN: %parse-mojo-isolated -verify-diagnostics %s
trait Marker:
pass
trait Refines(Marker):
pass
# ===========================================================================
# Opted out and listed again, explicitly
# ===========================================================================
struct OptOutThenList(
not Marker, # expected-note {{opted out here}}
# expected-error @below {{trait 'Marker' must not be listed and also opted out with 'not'; remove one of the entries}}
Marker,
):
var x: Int
# The order of the two entries does not matter: the error always lands on the
# plain entry and the note on the `not`.
struct ListThenOptOut(
# expected-error @below {{trait 'Marker' must not be listed and also opted out with 'not'; remove one of the entries}}
Marker,
not Marker, # expected-note {{opted out here}}
):
var x: Int
# The two spellings agreeing on false is still a repeated trait. This is the
# case the pre-existing "different constraints" check cannot see, because after
# canonicalization the propositions are equal.
struct OptOutThenWhereFalse(
not Marker, # expected-note {{opted out here}}
# expected-error @below {{trait 'Marker' must not be listed and also opted out with 'not'; remove one of the entries}}
Marker where False,
):
var x: Int
# ===========================================================================
# Opted out twice
# ===========================================================================
struct OptOutTwice(
not Marker, # expected-note {{first opted out here}}
# expected-error @below {{trait 'Marker' must be opted out at most once; remove the duplicate 'not'}}
not Marker,
):
var x: Int
# ===========================================================================
# Opted out and pulled back in transitively
# ===========================================================================
# `Refines` refines `Marker`, so conforming to it unconditionally requires
# `Marker` -- which this list opts out of.
struct OptOutAncestorOfListed(
not Marker, # expected-note {{opted out here}}
# expected-error @below {{trait 'Refines' requires ancestor trait 'Marker', which is opted out with 'not'; remove one of the entries}}
Refines,
):
var x: Int
# Same shape through the injected traits: `Copyable` refines `Movable`.
struct OptOutMovableKeepCopyable(
not Movable, # expected-note {{opted out here}}
# expected-error @below {{trait 'Copyable' requires ancestor trait 'Movable', which is opted out with 'not'; remove one of the entries}}
Copyable,
):
var x: Int
# ===========================================================================
# `not` combined with a `where` clause
# ===========================================================================
# `not Trait` already fixes the condition to false, so a second condition could
# only restate it or contradict it.
struct NotWithWhere[T: AnyType](
# expected-error @below {{'not' conformance does not support a 'where' clause}}
not Marker where conforms_to(T, Marker),
):
var x: Int
# ===========================================================================
# Malformed `not` entries
# ===========================================================================
struct RepeatedNot(
# expected-error @below {{'not' must not be repeated in a conformance entry}}
not not Marker,
):
var x: Int
struct NotAValue(
# expected-error @below {{expected a type, not a value}}
not 42,
):
var x: Int
# ===========================================================================
# Malformed `else "<reason>"` on a `not` entry
# ===========================================================================
# The reason is parsed by the same code as a `where ... else` message, so it
# carries the same restriction to string literals.
struct NotElseNonLiteral(
# expected-error @below {{the message in a 'not' conformance must be a string literal}}
not Marker else 42,
):
var x: Int
struct NotElseMissingMessage(
# expected-error @below {{expected a string literal message after 'else'}}
not Marker else,
):
var x: Int
# A reason needs something to explain. Without a `where` clause or a `not`,
# the entry is an unconditional conformance that cannot fail.
struct ElseWithoutCondition(
# expected-error @below {{a conformance message requires a 'where' clause or a 'not' conformance}}
Marker else "Marker is required",
):
var x: Int
# ===========================================================================
# A reason on `not Deinitable` competes with `@explicit_destroy`
# ===========================================================================
# Both name the message for abandoning the linear type the opt-out creates,
# so writing both is ambiguous rather than redundant.
# expected-error @below {{@explicit_destroy and the 'Deinitable' opt-out both give a message; keep only one}}
@explicit_destroy("use consume()")
struct DoubleLinearMessage(
# expected-note @below {{opt-out message written here}}
not Deinitable else "use release()",
):
var x: Int
# ===========================================================================
# `not` is a conformance condition, so it is struct-only
# ===========================================================================
# expected-error @below {{'not' conformances are only supported on structs}}
trait RefinementOptOut(not Marker):
pass
struct Extended:
var x: Int
# expected-error @below {{'not' conformances are only supported on structs}}
__extension Extended(not Marker):
pass
# A reason is a conformance condition too, so it is rejected before the entry
# gets far enough to be a `not`.
# expected-error @below {{conformance messages are only supported on structs}}
trait MessageOnRefinement(Marker else "Marker is required"):
pass
@@ -0,0 +1,190 @@
# ===----------------------------------------------------------------------=== #
# 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
##===----------------------------------------------------------------------===##
# Unpacking
##===----------------------------------------------------------------------===##
# expected-note @+1 {{function declared here}}
def test_unpack(d: Int):
# expected-error @+1 {{kwargs unpack can only satisfy another kwargs argument, it can't fulfill 'd'}}
test_unpack(**d)
# expected-error @+1 {{unpack is only supported when the callee accepts a variadic; to forward a runtime pack to a fixed-arity callee, route the call through a dispatcher whose argument is itself a variadic pack (e.g. `def shim[Ts: TypeList[Trait=AnyType, ...], //, callee: def(*args: *Ts) thin](...): callee(*pack)`)}}
test_unpack(*d)
# expected-error @+2 {{positional argument must not follow an unpack; move it before or convert to a keyword argument}}
# expected-note @+1 {{unpacked positional argument specified here}}
test_unpack(*d, d)
def test_unpack_twice(d: Int):
# expected-error @+2 {{unpack markers (*name syntax) must not appear more than once in a call; remove the second unpack}}
# expected-note @+1 {{previous unpacked positional argument specified here}}
test_unpack_twice(*d, *d)
# `f(*args, **kwargs)` is valid; the reverse order is not, matching Python.
def test_unpack_order(*args: Int, var **kwargs: Int):
# expected-error @+1 {{positional unpack must not follow keyword unpacking; move it before the '**' unpack}}
test_unpack_order(**kwargs, *args)
# expected-note @+1 {{function declared here}}
def test_merge_kwargs(var **kwargs: Int):
# expected-error @+2 {{combining a '**' unpack with other keyword arguments for '**kwargs' is not supported}}
# expected-note @+1 {{other keyword argument specified here}}
test_merge_kwargs(a=1, **kwargs^)
# expected-note @+1 {{function declared here}}
def test_two_kwargs_unpacks(var **kwargs: Int):
# expected-error @+2 {{combining a '**' unpack with other keyword arguments for '**kwargs' is not supported}}
# expected-note @+1 {{other keyword argument specified here}}
test_two_kwargs_unpacks(**kwargs^, **kwargs^)
# expected-note @below {{function declared here}}
def test_sum_intable[*Ts: Intable](*pack: *Ts):
pass
def test_forward_any_pack[*Ts: AnyType](*pack: *Ts):
# expected-error @+1 {{invalid call to 'test_sum_intable': cannot unpack a pack of type 'AnyType' ('Ts.values') into a call that expects a pack of type 'Intable' ('Ts.values')}}
test_sum_intable(*pack)
# Splatting a pack into a fixed-arity callee is not supported. The
# count-mismatch diagnostic should attach a hint pointing at the
# variadic-pack dispatcher pattern.
# expected-note @+1 {{function declared here}}
def takes_two_ints(x: Int, y: Int):
pass
def test_splat_into_fixed_arity[*Ts: AnyType](*pack: *Ts):
# expected-error @+1 {{unpack is only supported when the callee accepts a variadic; to forward a runtime pack to a fixed-arity callee, route the call through a dispatcher whose argument is itself a variadic pack (e.g. `def shim[Ts: TypeList[Trait=AnyType, ...], //, callee: def(*args: *Ts) thin](...): callee(*pack)`)}}
takes_two_ints(*pack)
# Resolved-pack splats: even when the operand's `VariadicPack` element list
# is statically known (here, by spelling concrete element types into the
# pack-typed parameter), splatting a pack into a fixed-arity callee is not
# supported. As with the symbolic case above, the call is diagnosed with
# the dispatcher-pattern hint regardless of whether the resolved element
# count is too few, too many, or an exact match for the callee's arity;
# `*pack`-to-positional expansion is follow-up work (MOCO-2210).
# expected-note @+1 {{function declared here}}
def takes_three_ints(a: Int, b: Int, c: Int):
pass
def test_resolved_pack_too_few(
pack: VariadicPack[origin=_, element_trait=AnyType, _, Int, Int]
):
# expected-error @+1 {{unpack is only supported when the callee accepts a variadic; to forward a runtime pack to a fixed-arity callee, route the call through a dispatcher whose argument is itself a variadic pack (e.g. `def shim[Ts: TypeList[Trait=AnyType, ...], //, callee: def(*args: *Ts) thin](...): callee(*pack)`)}}
takes_three_ints(*pack)
# expected-note @+1 {{function declared here}}
def takes_one_int(a: Int):
pass
def test_resolved_pack_too_many(
pack: VariadicPack[origin=_, element_trait=AnyType, _, Int, Int]
):
# expected-error @+1 {{unpack is only supported when the callee accepts a variadic; to forward a runtime pack to a fixed-arity callee, route the call through a dispatcher whose argument is itself a variadic pack (e.g. `def shim[Ts: TypeList[Trait=AnyType, ...], //, callee: def(*args: *Ts) thin](...): callee(*pack)`)}}
takes_one_int(*pack)
# expected-note @+1 {{function declared here}}
def takes_int_and_float(x: Int, y: Float64):
pass
def test_resolved_pack_matched_arity(
pack: VariadicPack[origin=_, element_trait=AnyType, _, Int, Float64]
):
# expected-error @+1 {{unpack is only supported when the callee accepts a variadic; to forward a runtime pack to a fixed-arity callee, route the call through a dispatcher whose argument is itself a variadic pack (e.g. `def shim[Ts: TypeList[Trait=AnyType, ...], //, callee: def(*args: *Ts) thin](...): callee(*pack)`)}}
takes_int_and_float(*pack)
# Unpacking into a *args (pos-vararg) function instead of a typed pack.
# Users may confuse *args-style variadics with typed packs.
# expected-note @+1 {{function declared here}}
def takes_varargs(*args: Int):
pass
def test_unpack_into_varargs[*Ts: AnyType](*pack: *Ts):
# expected-error @+1 {{value passed to 'args' cannot be converted from 'VariadicPack[False, Ts]' to 'VariadicList[Int, False]'}}
takes_varargs(*pack)
def test_unpack_varargs(*args: Int):
# expected-error @+1 {{unpack is only supported when the callee accepts a variadic; to forward a runtime pack to a fixed-arity callee, route the call through a dispatcher whose argument is itself a variadic pack (e.g. `def shim[Ts: TypeList[Trait=AnyType, ...], //, callee: def(*args: *Ts) thin](...): callee(*pack)`)}}
test_unpack(*args)
# Double-star unpacking a real **kwargs pack.
def takes_kwargs(var **kwargs: Int):
pass
def test_unpack_kwargs_pack(var **kwargs: Int):
# expected-error @below {{value of type 'StringDict[Int]' cannot be implicitly copied}}
# expected-note @below {{consider transferring the value with '^'}}
takes_kwargs(**kwargs)
# Ok!
takes_kwargs(**kwargs^)
# expected-note @+1 {{function declared here}}
def takes_varpack[*Ts: AnyType](*pack: *Ts):
pass
def test_positional_concat[*Ts: AnyType](*pack: *Ts):
# expected-error @below {{concatenating unpacked positional arguments is not supported}}
takes_varpack("hello", *pack)
# expected-error @below {{positional argument must not follow an unpack; move it before or convert to a keyword argument}}
# expected-note @below {{unpacked positional argument specified here}}
takes_varpack(*pack, "hello")
def test_unpack_twice[*Ts: AnyType](*pack: *Ts):
# expected-error @below {{unpack markers (*name syntax) must not appear more than once in a call; remove the second unpack}}
# expected-note @below {{previous unpacked positional argument specified here}}
takes_varpack(*pack, *pack)
# Splatting a non-VariadicPack type is not allowed.
struct MyStruct(Movable where False):
var x: Int
def __init__(out self, x: Int):
self.x = x
# expected-note @+1 {{function declared here}}
def takes_variadic_pack2[*Ts: AnyType](*pack: *Ts):
pass
def test_splat_non_pack():
var s = MyStruct(42)
# expected-error @+1 {{cannot unpack value of type 'MyStruct' into a variadic pack argument; expected a VariadicPack}}
takes_variadic_pack2(*s)
@@ -0,0 +1,61 @@
# ===----------------------------------------------------------------------=== #
# 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 -o /dev/null
# We should be able to infer something with a concrete origin even if it
# requires an upcast.
def takeA[origin: Origin, T: AnyType](ref[origin] a: String, b: T):
pass
def infer_ref_argument():
var s: String
var t: String
takeA(s, t) # Ok.
takeA[AnyOrigin[mut=True]](s, t) # Ok.
@fieldwise_init
struct TwoIntParamStruct[a: Int, b: Int](Movable where False):
pass
# expected-note @below {{function declared here}}
def take_two_int_dep[x: Int](a: TwoIntParamStruct[x, x + 1]):
pass
# expected-note @+1 {{function declared here}}
def take_tied_values[
first1: Int, first2: Int, second: Int
](a: TwoIntParamStruct[first1, second], b: TwoIntParamStruct[first2, second],):
pass
def infer_two_param_dep_struct[y: Int]():
take_two_int_dep(TwoIntParamStruct[1, 2]())
# expected-error @+2 {{invalid call to 'take_two_int_dep': value passed to 'a' cannot be converted from 'TwoIntParamStruct[Int(2), Int(2)]' to 'TwoIntParamStruct[Int(2), Int(3)]'}}
# expected-note @+1 {{.b of the first value is 'Int(2)' but the second value is 'Int(3)'}}
take_two_int_dep(TwoIntParamStruct[2, 2]())
take_two_int_dep(TwoIntParamStruct[b=2, a=1]())
take_two_int_dep(TwoIntParamStruct[y, y + 1]())
# expected-error @+2 {{invalid call to 'take_two_int_dep': value passed to 'a' cannot be converted from 'TwoIntParamStruct[y, (y + Int(2))]' to 'TwoIntParamStruct[y, (y + Int(1))]'}}
# expected-note @+1 {{.b of the first value is '(y + Int(2))' but the second value is '(y + Int(1))'}}
take_two_int_dep(TwoIntParamStruct[y, y + 2]())
# expected-error @+2 {{invalid call to 'take_tied_values': value passed to 'b' cannot be converted from 'TwoIntParamStruct[Int(20), Int(2)]' to 'TwoIntParamStruct[Int(20), Int(1)]'}}
# expected-note @+1 {{.b of the first value is 'Int(2)' but the second value is 'Int(1)'}}
take_tied_values(TwoIntParamStruct[10, 1](), TwoIntParamStruct[20, 2]())
@@ -0,0 +1,92 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
# RUN: %parse-mojo-isolated -verify-diagnostics %s
# expected-note @+1 {{function declared here}}
def bind_fat_to_thin_target[g: def(y: Int) thin -> Int](x: Int):
pass
def bind_fat_to_thin_main():
var x = 4
@__copy_capture(x)
@__parameter
def g(y: Int) -> Int:
return x
# expected-error @below {{'bind_fat_to_thin_target' parameter 'g' has 'def(y: Int) thin -> Int' type, but value has type 'def(y: Int) capturing thin -> Int'}}
comptime Bound = bind_fat_to_thin_target[g]
Bound(3)
def makeClosure(x: Int):
var z = x + x
@__copy_capture(z)
@__parameter
def writer() -> Int:
# expected-error @below {{expression must be mutable in assignment}}
z = z + z
return z
var y = writer()
@fieldwise_init
struct MemType(Movable where False):
var a: Int
def foo(self) -> MemType:
return MemType(self.a + self.a)
struct NoCopyType(RegisterPassable):
var a: Int
@implicit
def __init__(out self, aa: Int):
self.a = aa
def foo(self) -> NoCopyType:
return NoCopyType(self.a + self.a)
@no_inline
def makeClosure(x: MemType):
var rp: NoCopyType = NoCopyType(x.a)
# expected-error @below {{value of type 'NoCopyType' cannot be implicitly copied, it does not conform to 'ImplicitlyCopyable'}}
# expected-note @below {{consider transferring the value with '^'}}
@__copy_capture(rp)
@__parameter
def writer() -> Int:
pass
def bad_capture(x: Int):
var z = x
# expected-error @below {{cannot capture unknown value 'not_a_thing'}}
@__copy_capture(not_a_thing)
@__parameter
__async def closure_1():
pass
# expected-error @below {{cannot capture unknown value 'not_a_thing'}}
@__move_capture(not_a_thing)
@__parameter
__async def closure_2():
pass
@@ -0,0 +1,57 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
# RUN: %parse-mojo-isolated -verify-diagnostics %s 2>&1
# A `where` clause on a SIMD constructor whose predicate transitively requires
# the constructor being constrained creates a declaration cycle that poisons
# the `Int` constructor set. Inferring the `__literal_size__` parameter of a
# list-literal constructor materializes an `Int`, so it hits the poisoned set;
# ensure that failure is reported as a normal overload-resolution error instead
# of crashing.
@fieldwise_init
struct Wrapper(ImplicitlyCopyable, RegisterPassable):
pass
def pred(arg: Int) -> Bool:
return True
__extension SIMD:
@implicit
# expected-error @below {{attempt to resolve a recursive reference to declaration '__init__'}}
# expected-note @below {{referenced from here}}
# expected-note @below {{by declaration '__init__'}}
# expected-error @below {{failed to emit constraint expression}}
def __init__(out self, arg: Wrapper) where pred(0):
self = {}
# expected-note @below {{candidate not viable: missing required argument: 'move'}}
# expected-note @below {{def __init__(out self, *, deinit move: Self) # note - generated function}}
struct MyList[T: AnyType]:
# expected-note @below {{candidate not viable: cannot infer the size of the list literal with a previously diagnosed error}}
def __init__[*, __literal_size__: Int](
out self,
var *elements: Self.T,
__list_literal__: NoneType,
):
pass
def trigger():
# expected-note @below {{referenced through this use}}
# expected-error @below {{no matching function in initialization}}
var x: MyList[Wrapper] = [Wrapper(), Wrapper()]
@@ -0,0 +1,135 @@
# ===----------------------------------------------------------------------=== #
# 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.
# ===----------------------------------------------------------------------=== #
# Negative cases for body-constraint discharge: bindings whose body
# constraints are concrete and violated, or concrete and unprovable,
# should fail with a diagnostic at the binding site.
# RUN: %parse-mojo-isolated -verify-diagnostics %s
##===----------------------------------------------------------------------===##
# Single-variable alias, violation at full binding
##===----------------------------------------------------------------------===##
comptime pos_only[x: Int]
# expected-note @below {{constraint declared here evaluated to False}}
where x > 0 = x
def use_single_var_violation():
# expected-error @below {{violated constraint}}
comptime bad = pos_only[-1]
##===----------------------------------------------------------------------===##
# Multi-variable alias, violation at full binding
##===----------------------------------------------------------------------===##
# Both parameters are bound to literals that make `x < y` false; the
# constraint is concrete and provably violated.
comptime ordered_pair[x: Int, y: Int]
# expected-note @below {{constraint declared here evaluated to False}}
where x < y = x + y
def use_multi_var_violation():
# expected-error @below {{violated constraint}}
comptime bad = ordered_pair[5, 3]
##===----------------------------------------------------------------------===##
# Multi-variable alias, violation by the concrete part of a partial bind
##===----------------------------------------------------------------------===##
# `where x > 0` references only `x`. Binding `x = -1` makes that part
# of the constraint concrete and false even though `y` is still
# unbound; the partial binding fails.
comptime needs_x_positive[x: Int, y: Int]
# expected-note @below {{constraint declared here evaluated to False}}
where x > 0 = x + y
def use_partial_bind_violation():
# expected-error @below {{violated constraint}}
comptime bad = needs_x_positive[-1, _]
##===----------------------------------------------------------------------===##
# Single-variable alias, parametric binding without evidence
##===----------------------------------------------------------------------===##
# The bound value is the caller's parameter `K`. After substitution the
# constraint is `K > 0`, which is concrete (no unbound parameters) but
# unprovable here because the caller carries no `where K > 0` clause.
comptime needs_positive[x: Int]
# expected-note @below {{constraint declared here needs evidence for}}
where x > 0 = x
def use_unprovable[K: Int]():
# expected-error @below {{lacking evidence to prove correctness}}
comptime z = needs_positive[K]
##===----------------------------------------------------------------------===##
# `and` constraint, both conjuncts concrete, one false
##===----------------------------------------------------------------------===##
# `and(x > 0, y > 0)` with `x = 5, y = -1` folds to False, so the
# binding fails.
comptime and_pos[x: Int, y: Int]
# expected-note @below {{constraint declared here evaluated to False}}
where x > 0 and y > 0 = x + y
def use_and_full_violation():
# expected-error @below {{violated constraint}}
comptime bad = and_pos[5, -1]
##===----------------------------------------------------------------------===##
# `or` constraint, both disjuncts concrete and false
##===----------------------------------------------------------------------===##
comptime or_pos[x: Int, y: Int]
# expected-note @below {{constraint declared here evaluated to False}}
where x > 0 or y > 0 = x + y
def use_or_full_violation():
# expected-error @below {{violated constraint}}
comptime bad = or_pos[-1, -2]
##===----------------------------------------------------------------------===##
# Function symbol, violation at full binding
##===----------------------------------------------------------------------===##
# expected-note @below {{function declared here}}
def need_pos[x: Int, y: Int]()
# expected-note @below {{constraint declared here evaluated to False}}
where x > 0:
pass
def use_fn_violation():
# expected-error @below {{violated constraint}}
need_pos[-1, 3]()
@@ -0,0 +1,210 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
# Test struct-level trailing `where` body constraints. These constraints are
# checked during parameter inference (`InferenceState::checkBodyConstraints`)
# at every site that binds the struct's parameters, so a violation surfaces
# at instantiation rather than at first use of an instance.
#
# Each section uses its own struct/function decl so per-section diagnostic
# notes don't bleed across test sites (mirrors the convention in
# `constraint_overload_errors.mojo`).
# RUN: %parse-mojo-isolated -verify-diagnostics %s
##===----------------------------------------------------------------------===##
# Satisfied body constraint at instantiation - positive case
##===----------------------------------------------------------------------===##
# Verifies the new `checkBodyConstraints` path doesn't produce false
# positives on the happy path.
struct SatisfiedStruct[N: Int]
(Movable where False) where N > 0:
pass
def use_satisfied_struct():
var x: SatisfiedStruct[5]
##===----------------------------------------------------------------------===##
# Violated body constraint at instantiation
##===----------------------------------------------------------------------===##
# Binding `N = -1` violates `N > 0`. The new check folds this into a
# binding-time error rather than letting it leak into downstream uses.
# expected-note @below {{'ViolatedStruct' declared here}}
struct ViolatedStruct[N: Int]
# expected-note @below {{constraint declared here evaluated to False}}
(Movable where False) where N > 0:
pass
def use_violated_struct():
# expected-error @below {{violated constraint}}
var x: ViolatedStruct[-1]
##===----------------------------------------------------------------------===##
# Unprovable body constraint without evidence (Issue #1 regression)
##===----------------------------------------------------------------------===##
# When the caller is itself parametric and offers no assumption that
# discharges the body constraint, the binding is unprovable. The fix in
# `ParamInf::inferForStruct` ensures the strict (non-discarding) path
# returns a single "lacking evidence" error and does NOT silently return
# valid bindings while emitting a top-level error against the same site.
# expected-note @below {{cannot prove constraint}}
struct UnprovableStruct[N: Int]
# expected-note @below {{constraint declared here needs evidence for}}
(Movable where False) where N > 0:
pass
def use_unprovable_struct[K: Int]():
# expected-error @below {{lacking evidence to prove correctness}}
var x: UnprovableStruct[K]
##===----------------------------------------------------------------------===##
# Unprovable body constraint dischargeable from caller's assumptions
##===----------------------------------------------------------------------===##
# The caller's `where K > 0` is threaded through as an additional assumption
# during constraint checking, so the body constraint is provable.
struct DischargeableStruct[N: Int]
(Movable where False) where N > 0:
pass
def use_dischargeable_struct[K: Int]() where K > 0:
var x: DischargeableStruct[K]
##===----------------------------------------------------------------------===##
# Body constraint enforced at function-signature type formation
##===----------------------------------------------------------------------===##
# A function signature that mentions a parameterized struct re-enters
# `inferForStruct` to type-check the parameter type itself. Unprovable body
# constraints from that site are collected by the deferral feature and
# discharged later in `TypeCheckedParamList::emitBodyConstraints` using the
# trailing `where` clauses as additional assumptions (see
# `body_constraint_deferral.mojo` for positive-discharge coverage). When no
# trailing `where` clause can discharge the deferred constraint, the
# discharge step surfaces a hard error here. (The function-body analog is
# covered above by `use_dischargeable_struct`, where the trailing `where`
# is already in scope at the binding site.)
struct PositiveOnly[N: Int]
# expected-note @below {{constraint declared here needs evidence for}}
(Movable where False) where N > 0:
pass
# expected-error @below {{lacking evidence to prove correctness}}
# expected-note @below {{add a trailing 'where' clause that requires '(K > Int(0))'}}
def bad_signature_use[K: Int](x: PositiveOnly[K]):
pass
def call_bad_signature_use():
var p: PositiveOnly[7]
##===----------------------------------------------------------------------===##
# Multi-parameter body constraint
##===----------------------------------------------------------------------===##
# A constraint that mentions two parameters must be checked once both are
# bound, and yield a hard binding-time error when violated.
struct OrderedPair[A: Int, B: Int]
(Movable where False) where A < B:
pass
def use_ordered_pair_satisfied():
var p: OrderedPair[1, 5]
# expected-note @below {{'ViolatedOrderedPair' declared here}}
struct ViolatedOrderedPair[A: Int, B: Int]
# expected-note @below {{constraint declared here evaluated to False}}
(Movable where False) where A < B:
pass
def use_ordered_pair_violated():
# expected-error @below {{violated constraint}}
var p: ViolatedOrderedPair[5, 1]
##===----------------------------------------------------------------------===##
# Body constraint references trait conformance
##===----------------------------------------------------------------------===##
# A struct gated on `conforms_to` should only accept type bindings whose
# inferred parameter satisfies the trait. This is the value-level analog of
# the existing trait-conformance verification flow but applied at struct
# instantiation rather than at conformance declaration.
struct OnlyIntableSatisfied[T: AnyType]
(Movable where False) where conforms_to(T, Intable):
pass
struct ConcreteIntable(Intable, Movable where False):
def __int__(self) -> Int:
return 0
def use_intable_satisfied():
var x: OnlyIntableSatisfied[ConcreteIntable]
# expected-note @below {{'OnlyIntableViolated' declared here}}
struct OnlyIntableViolated[T: AnyType]
# expected-note @below {{constraint declared here evaluated to False}}
(Movable where False) where conforms_to(T, Intable):
pass
struct NotIntable(Movable where False):
pass
def use_intable_violated():
# expected-error @below {{violated constraint}}
var x: OnlyIntableViolated[NotIntable]
# expected-note @below {{cannot prove constraint}}
struct OnlyIntableUnprovable[T: AnyType]
# expected-note @below {{constraint declared here needs evidence for}}
(Movable where False) where conforms_to(T, Intable):
pass
def use_intable_dischargeable[T: AnyType]() where conforms_to(T, Intable):
var x: OnlyIntableUnprovable[T]
def use_intable_unprovable[T: AnyType]():
# expected-error @below {{lacking evidence to prove correctness}}
var x: OnlyIntableUnprovable[T]
@@ -0,0 +1,76 @@
# ===----------------------------------------------------------------------=== #
# 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
struct PCall(Movable where False):
def __init__(out self):
pass
def __call__[x: Int](ref self, y: Int) -> Int:
return x + y
struct PCallWithGetItem(Movable where False):
def __init__(out self):
pass
# expected-warning @below {{parametric '__call__' method cannot be called directly because 'PCallWithGetItem' defines '__getitem__', '__setitem__', or '__getattr__'; consider using a different name for this method}}
def __call__[x: Int](ref self, y: Int) -> Int:
return x + y
# expected-note @below {{__getitem__ defined here}}
def __getitem__(ref self, y: Int) -> Int:
return y
# expected-note @below {{__getitem__ defined here}}
def __getitem__(ref self, y: StringLiteral) -> Int:
return 2
struct PCallWithGetAttr(Movable where False):
def __init__(out self):
pass
# expected-warning @below {{parametric '__call__' method cannot be called directly because 'PCallWithGetAttr' defines '__getitem__', '__setitem__', or '__getattr__'; consider using a different name for this method}}
def __call__[_x: StringLiteral](ref self):
pass
# expected-note @below {{__getattr__ defined here}}
def __getattr__[x: StringLiteral](self) -> Int:
return 2
# Note: Test heuristic fix for MOCO-2833
struct PCallWithGetItemAndInferredParameters(Movable where False):
def __init__(out self):
pass
# This does *not* produce a warning, because the parameters are all
# inferred.
def __call__[T: Movable, //](ref self, var y: T) -> T:
return y^
def __getitem__(ref self, y: Int) -> Int:
return y
def main():
var pc = PCall()
_ = pc[1](2)
# verifying that we don't break structs with __getitem__ defined
var pcgi = PCallWithGetItem()
_ = pcgi[1]( # expected-error {{'Int' does not implement the '__call__' method}}
2
)
@@ -0,0 +1,90 @@
# ===----------------------------------------------------------------------=== #
# 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 errors for duplicate traits with conflicting conditional conformances
# in struct inheritance lists.
#
# When the same trait appears multiple times in a struct's inheritance list
# (either directly or through trait compositions), the conditional conformance
# constraints must agree.
# RUN: %parse-mojo-isolated -verify-diagnostics %s
# ===========================================================================
# Duplicate trait: unconditional + conditional
# ===========================================================================
trait DupTraitA:
pass
struct DupUnconditionalAndConditional[T: Movable](
DupTraitA,
# expected-error @below {{trait 'DupTraitA' appears multiple times in the conformance list with different constraints}}
DupTraitA where conforms_to(T, Copyable),
Movable,
):
var data: Self.T
def __init__(out self, var data: Self.T):
self.data = data^
# ===========================================================================
# Duplicate trait: different conditional constraints
# ===========================================================================
trait DupTraitB:
pass
struct DupDifferentConstraints[T: Movable](
DupTraitB where conforms_to(T, Copyable),
# expected-error @below {{trait 'DupTraitB' appears multiple times in the conformance list with different constraints}}
DupTraitB where conforms_to(T, Intable),
Movable,
):
var data: Self.T
def __init__(out self, var data: Self.T):
self.data = data^
# ===========================================================================
# Trait composition + standalone with conflicting constraints
# ===========================================================================
# A & B where cond gives both A and B the condition. Listing A again without
# a condition conflicts.
trait CompA:
pass
trait CompB:
pass
struct CompositionConflictsWithStandalone[T: Movable](
CompA & CompB where conforms_to(T, Copyable),
# expected-error @below {{trait 'CompA' appears multiple times in the conformance list with different constraints}}
CompA,
Movable,
):
var data: Self.T
def __init__(out self, var data: Self.T):
self.data = data^
@@ -0,0 +1,590 @@
# ===----------------------------------------------------------------------=== #
# 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 errors for conditional trait conformance.
# These errors are detected during struct declaration parsing and conformance
# verification, before any instantiation occurs.
#
# NOTE: Declaration-time errors (diamond, ancestor) are tested first because
# they are emitted before method constraint errors during parsing.
# RUN: %parse-mojo-isolated -verify-diagnostics %s
# ===========================================================================
# Diamond with different constraints requires explicit Base
# ===========================================================================
# When a struct conditionally conforms to DerivedA and DerivedB with different
# constraints, and both inherit from Base, the user must explicitly list Base.
trait DiamondBase:
pass
trait DiamondDerivedA(DiamondBase):
pass
trait DiamondDerivedB(DiamondBase):
pass
struct DiamondMissingExplicitBase[T: Movable & Deinitable](
# expected-error @below {{ancestor trait 'DiamondBase' is reached via multiple inheritance paths with different constraints; it must be explicitly listed in the conformance list with the desired constraint}}
DiamondDerivedA where conforms_to(T, Copyable),
DiamondDerivedB where conforms_to(T, Intable),
Movable,
):
var data: Self.T
def __init__(out self, var data: Self.T):
self.data = data^
# ===========================================================================
# Derived constraint must imply ancestor constraint
# ===========================================================================
# When both a derived trait and its ancestor are explicitly listed with
# constraints, the derived constraint must logically imply the ancestor's.
trait AncestorImplicationBase:
pass
trait AncestorImplicationDerived(AncestorImplicationBase):
pass
struct DerivedDoesNotImplyAncestor[T: Movable & Deinitable](
# Base requires Intable
AncestorImplicationBase where conforms_to(T, Intable),
# But Derived only requires Copyable - this doesn't imply Intable!
# expected-error @below {{constraint for 'AncestorImplicationDerived' does not imply constraint for ancestor trait 'AncestorImplicationBase'; strengthen the derived constraint by adding the ancestor's constraint with 'and'}}
AncestorImplicationDerived where conforms_to(T, Copyable),
Movable,
):
var data: Self.T
def __init__(out self, var data: Self.T):
self.data = data^
# ===========================================================================
# Unconditional derived with conditional ancestor
# ===========================================================================
# When a derived trait is listed unconditionally but its ancestor is explicitly
# listed conditionally, this is inconsistent: the derived trait always requires
# the ancestor, so the ancestor cannot be conditional.
trait UnconditionalDerivedBase:
pass
trait UnconditionalDerivedChild(UnconditionalDerivedBase):
pass
struct UnconditionalDerivedConditionalAncestor[T: Movable & Deinitable](
# Derived is unconditional - always conforms
Movable,
# But ancestor is conditional - inconsistent!
UnconditionalDerivedBase where conforms_to(T, Copyable),
# expected-error @below {{constraint for 'UnconditionalDerivedChild' does not imply constraint for ancestor trait 'UnconditionalDerivedBase'; strengthen the derived constraint by adding the ancestor's constraint with 'and'}}
UnconditionalDerivedChild,
):
var data: Self.T
def __init__(out self, var data: Self.T):
self.data = data^
# ===========================================================================
# Conditional conformance to TrivialRegisterPassable is not supported
# ===========================================================================
# TrivialRegisterPassable depends on struct body (field triviality) which
# creates parser cycle risks and requires composing the user's where-clause
# with field-level triviality witnesses.
struct ConditionalTrivialRegPassable[T: Movable & Deinitable](
Movable,
# expected-error @below {{conditional conformance to 'TrivialRegisterPassable' is not supported}}
TrivialRegisterPassable where conforms_to(T, TrivialRegisterPassable),
):
var value: Self.T
def __init__(out self, var value: Self.T):
self.value = value^
# ===========================================================================
# Conditional conformance to RegisterPassable IS allowed
# ===========================================================================
# The struct stays pessimistically MemoryOnly at declaration time; the
# parametric isMemoryOnly bit resolves per-instantiation during lowering.
struct ConditionalRegPassable[T: Movable & Deinitable](
Movable,
RegisterPassable where conforms_to(T, RegisterPassable),
):
var value: Self.T
def __init__(out self, var value: Self.T):
self.value = value^
# Origin rejection: returning an origin of a conditionally-RP argument is
# rejected because the type might expand to RegisterPassable (in which case
# the argument would be promoted to a register and the origin would dangle).
# expected-error @+3 {{cannot return 'x's origin, because it might expand to a RegisterPassable type}}
def bad_conditional_rp_origin[
T: Movable & Deinitable
](x: ConditionalRegPassable[T]) -> ref[x] ConditionalRegPassable[T]:
return x
# Workaround: using `ref` convention forces indirect passing, so the argument
# always has a stable memory address regardless of RP status. This must compile.
def ok_conditional_rp_ref_origin[
T: Movable & Deinitable
](ref x: ConditionalRegPassable[T]) -> ref[x] ConditionalRegPassable[T]:
return x
# ===========================================================================
# RP trait conformance with weaker constraint
# ===========================================================================
# When a struct has explicit RegisterPassable with constraint C_rp and also
# conforms to a derived RP trait with a weaker constraint C_conf, the
# ancestor implication check in DeclResolution.cpp rejects it (fires first).
# verifyAndBuildConformance in Traits.cpp has an independent implication
# check as defense-in-depth.
trait RPRequiringTrait(RegisterPassable):
def rp_trait_method(self) -> Int:
...
struct RPTraitWeakerConstraint[T: Movable & Deinitable](
Movable,
# expected-error @below {{constraint for 'RPRequiringTrait' does not imply constraint for ancestor trait 'RegisterPassable'}}
RPRequiringTrait where conforms_to(T, Movable),
RegisterPassable where conforms_to(T, RegisterPassable),
):
var value: Self.T
def __init__(out self, var value: Self.T):
self.value = value^
def rp_trait_method(self) -> Int:
return 42
# ===========================================================================
# Non-RP struct conditionally conforming to RP trait
# ===========================================================================
# A struct with NO RegisterPassable conformance that conditionally conforms
# to a trait inheriting from RegisterPassable. The canonical trait
# propagation adds RegisterPassable as an ancestor with the same constraint,
# so the struct ends up with conditional RP matching the conformance — the
# implication check in verifyAndBuildConformance passes trivially.
# This test documents that such usage is accepted (no error expected).
struct NoExplicitRPConformsToRPTrait[T: Deinitable & Movable](
Deinitable,
Movable,
RPRequiringTrait where conforms_to(T, RegisterPassable),
):
var value: Self.T
def __init__(out self, var value: Self.T):
self.value = value^
def rp_trait_method(self) -> Int:
return 42
# ===========================================================================
# Unconditional conformance with conditional method
# ===========================================================================
# A struct that unconditionally claims to conform to a trait, but the method
# implementing the trait requirement has a constraint that can't be proven
# from nothing (the unconditional conformance provides no assumptions).
# expected-note @below {{trait 'UnconditionalConformanceTrait' declared here}}
trait UnconditionalConformanceTrait:
# expected-note @+2 {{required by trait method here}}
# expected-note @below {{invalid reference to 'do_something': lacking evidence to prove correctness}}
def do_something(self):
...
# expected-error @+2 {{does not implement all requirements for 'UnconditionalConformanceTrait'}}
# expected-note @below {{provide evidence for the constraint here to aid in candidate selection}}
struct UnconditionalWithConditionalMethod[x: Int](
Movable, UnconditionalConformanceTrait
):
# expected-note @+2 {{cannot prove constraint for candidate}}
# expected-note @below {{constraint declared here needs evidence for '(x > Int(10))'}}
def do_something(self) where Self.x > 10:
pass
# ===========================================================================
# Conditional conformance with non-implied method constraint
# ===========================================================================
# A struct that conditionally conforms to a trait (requires T: Intable),
# but the method has a different constraint (requires T: Copyable) that
# cannot be proven from the conformance constraint.
# expected-note @below {{trait 'MismatchedConstraintTrait' declared here}}
trait MismatchedConstraintTrait:
# expected-note @+2 {{required by trait method here}}
# expected-note @below {{invalid reference to 'process': lacking evidence to prove correctness}}
def process(self):
...
# expected-error @+2 {{does not implement all requirements for 'MismatchedConstraintTrait'}}
# expected-note @below {{provide evidence for the constraint here to aid in candidate selection}}
struct MismatchedConstraints[T: Movable](
MismatchedConstraintTrait where conforms_to(T, Intable), Movable
):
# This method requires Copyable, but conformance only guarantees Intable
# expected-note @+2 {{cannot prove constraint for candidate}}
# expected-note @below {{constraint declared here needs evidence for 'conforms_to(T, Copyable)'}}
def process(self) where conforms_to(Self.T, Copyable):
pass
# ===========================================================================
# Weaker conformance constraint with stronger method constraint
# ===========================================================================
# A struct with a weaker conformance constraint (T: Copyable) but a method
# that requires a stronger constraint (T: Copyable AND Intable).
# expected-note @below {{trait 'WeakerConformanceTrait' declared here}}
trait WeakerConformanceTrait:
# expected-note @+2 {{required by trait method here}}
# expected-note @below {{invalid reference to 'execute': lacking evidence to prove correctness}}
def execute(self):
...
# expected-error @+2 {{does not implement all requirements for 'WeakerConformanceTrait'}}
# expected-note @below {{provide evidence for the constraint here to aid in candidate selection}}
struct WeakerConformanceStrongerMethod[T: Movable](
Movable,
WeakerConformanceTrait where conforms_to(T, Copyable),
):
# This method requires BOTH Copyable AND Intable, but conformance only guarantees Copyable
# expected-note @below {{cannot prove constraint for candidate}}
def execute(
self,
# expected-note @below {{constraint declared here needs evidence for 'conforms_to(T, Intable) if conforms_to(T, Copyable) else conforms_to(T, Copyable)'}}
) where conforms_to(Self.T, Copyable) and conforms_to(Self.T, Intable):
pass
# ===========================================================================
# Conditional conformance with both unconditional and conditional methods
# ===========================================================================
# A struct with conditional conformance where both an unconditional method and
# a conditional method (whose constraint is implied) exist. Both are valid
# candidates, causing ambiguity.
# expected-note @below {{trait 'AmbiguousMethodTrait' declared here}}
trait AmbiguousMethodTrait:
# expected-note @below {{ambiguous use of 'perform'}}
def perform(self):
...
# expected-error @below {{does not implement all requirements for 'AmbiguousMethodTrait'}}
struct AmbiguousUnconditionalAndConditional[T: Movable](
AmbiguousMethodTrait where conforms_to(T, Copyable),
Movable,
):
# Unconditional method - always valid
# expected-note @below {{candidate declared here}}
def perform(self):
pass
# Conditional method - also valid because conformance implies T: Copyable
# expected-note @below {{candidate declared here}}
def perform(self) where conforms_to(Self.T, Copyable):
pass
# ===========================================================================
# Multiple conditional methods both implied by stronger conformance
# ===========================================================================
# A struct with a strong conformance constraint (T: Copyable AND T: Intable)
# but two methods with weaker, different constraints. Both are implied by the
# conformance, causing ambiguity.
# expected-note @below {{trait 'MultipleConditionsTrait' declared here}}
trait MultipleConditionsTrait:
# expected-note @below {{ambiguous use of 'run'}}
def run(self):
...
# expected-error @below {{does not implement all requirements for 'MultipleConditionsTrait'}}
struct AmbiguousBothConditional[T: Movable](
Movable,
MultipleConditionsTrait where conforms_to(T, Copyable) and conforms_to(
T, Intable
),
):
# Method requiring Copyable - implied by conformance
# expected-note @below {{candidate declared here}}
def run(self) where conforms_to(Self.T, Copyable):
pass
# Method requiring Intable - also implied by conformance
# expected-note @below {{candidate declared here}}
def run(self) where conforms_to(Self.T, Intable):
pass
# ===========================================================================
# Unprovable overload causes error even with a valid candidate
# ===========================================================================
# Following overload selection rules, ALL candidates' constraints must be
# definitively provable or disproved. If any candidate has unprovable
# constraints (constraints we can neither prove nor disprove from the
# conformance), we error - even if another candidate has provable constraints.
#
# This prevents ambiguity: the user might have intended the unprovable
# candidate to be selected, but our constraint system can't verify that.
# expected-note @below {{trait 'UnprovableCandidateTrait' declared here}}
trait UnprovableCandidateTrait:
# expected-note @+2 {{required by trait method here}}
# expected-note @below {{ambiguous reference to 'handle': lacking evidence to select candidate}}
def handle(self):
...
# expected-error @+2 {{does not implement all requirements for 'UnprovableCandidateTrait'}}
# expected-note @below {{provide evidence for or against the constraints here to aid in candidate selection}}
struct UnprovableWithValidCandidate[T: Movable](
Movable,
UnprovableCandidateTrait where conforms_to(T, Copyable),
):
# Unprovable: Intable is unrelated to Copyable - can't prove or disprove.
# expected-note @+2 {{cannot prove constraint for candidate}}
# expected-note @below {{constraint declared here needs evidence for 'conforms_to(T, Intable)'}}
def handle(self) where conforms_to(Self.T, Intable):
pass
# Provable: Copyable matches the conformance constraint.
# But we still error because we can't rule out the above candidate.
# expected-note @below {{candidate is valid but cannot be selected until other candidates are disproved}}
def handle(self) where conforms_to(Self.T, Copyable):
pass
# ===========================================================================
# Method with `where not` is disproved (contradicts conformance)
# ===========================================================================
# When a method has `where not X` and the conformance requires X, the method
# is "disproved" - definitively not a valid candidate. This is different from
# "unprovable" because we CAN make a determination (it's definitely invalid).
#
# A disproved candidate is simply not a candidate, so the requirement goes
# unwitnessed. The candidate is still listed with its `where` clause, so the
# contradiction with the conformance is visible.
# expected-note @below {{trait 'ContradictingConstraintTrait' declared here}}
trait ContradictingConstraintTrait:
# expected-note @below {{no 'apply' candidates have type 'def(self: DisprovedWithWhereNot[T]) thin -> None'}}
def apply(self):
...
# expected-error @below {{does not implement all requirements for 'ContradictingConstraintTrait'}}
struct DisprovedWithWhereNot[T: Movable](
ContradictingConstraintTrait where conforms_to(T, Copyable),
Movable,
):
# Disproved: `not conforms_to(T, Copyable)` contradicts conformance.
# expected-note @below {{candidate declared here with type 'def[T: Movable, //](self: DisprovedWithWhereNot[T]) thin -> None where not conforms_to(T, Copyable).__bool__()'}}
def apply(self) where not conforms_to(Self.T, Copyable):
pass
# ===========================================================================
# Synthesized default trait method gated by conformance constraint
# ===========================================================================
# When a struct conditionally conforms to a trait, synthesized default method
# wrappers must carry the conformance constraint. Calling the default method
# without evidence that the constraint is satisfied should be rejected.
trait DefaultMethodTrait:
def custom_default(self) -> Int:
return 42
# expected-note @below {{cannot prove constraint for candidate}}
# expected-note @below {{def custom_default(self) -> Int where conforms_to(T, Copyable) # note - generated function}}
struct ConditionalDefaultMethod[T: Movable](
# expected-note @below {{constraint declared here}}
DefaultMethodTrait where conforms_to(T, Copyable),
Movable,
):
def __init__(out self):
pass
def call_default_externally[T: Movable](x: ConditionalDefaultMethod[T]):
# expected-error @below {{lacking evidence to prove correctness}}
# expected-note @below {{provide evidence for the constraint}}
var a = x.custom_default()
# ===========================================================================
# Zero-field struct: synthesized copy/move init gated by constraint
# ===========================================================================
# A zero-field struct with conditional conformance. The compiler auto-
# synthesizes an empty copy/move init whose body trivially succeeds, so
# the conformance constraint on the defOp is the only thing preventing
# misuse.
trait ZeroFieldTrait:
def zero_field_method(self) -> Int:
return 0
# expected-note @below {{cannot prove constraint for candidate}}
# expected-note @below {{def zero_field_method(self) -> Int where conforms_to(T, Copyable) # note - generated function}}
struct ZeroFieldConditional[T: Movable](
Movable,
# expected-note @below {{constraint declared here needs evidence for 'conforms_to(T, Copyable)'}}
ZeroFieldTrait where conforms_to(T, Copyable),
):
def __init__(out self):
pass
def call_on_zero_field[T: Movable](x: ZeroFieldConditional[T]):
# expected-error @below {{lacking evidence to prove correctness}}
# expected-note @below {{provide evidence for the constraint}}
var a = x.zero_field_method()
# ===========================================================================
# OR-gated constraint does not provide definite conformance for copy synthesis
# ===========================================================================
# When the conditional Copyable conformance uses an OR constraint, the
# compiler cannot determine which branch holds, so it cannot synthesize a
# copy constructor via trait downcast. This tests that
# constraintImpliesConformance correctly rejects OR disjuncts.
struct CopySynthFailsWithOR[T: Deinitable & Movable](
Copyable where conforms_to(T, Copyable) or conforms_to(T, Intable),
Deinitable,
Movable,
):
# expected-error @below {{cannot synthesize copy constructor because field 'value' has non-copyable type}}
var value: Self.T
def __init__(out self, var value: Self.T):
self.value = value^
# ===========================================================================
# Multi-field struct where constraint only covers one parameter
# ===========================================================================
# The Copyable conformance constraint mentions T but not U. The synthesized
# copy constructor can trait-downcast T (covered by the constraint) but has
# no evidence for U, so copy synthesis must fail on the second field.
struct CopySynthFailsMultiField[
T: Deinitable & Movable,
U: Deinitable & Movable,
](
Copyable where conforms_to(T, Copyable),
Deinitable,
Movable,
):
var first: Self.T
# expected-error @below {{cannot synthesize copy constructor because field 'second' has non-copyable type}}
var second: Self.U
def __init__(out self, var first: Self.T, var second: Self.U):
self.first = first^
self.second = second^
# ===========================================================================
# comptime member constraint not implied by the conformance constraint
# ===========================================================================
# A conditional conformance discharges a comptime member's trailing `where`
# clause only when the conformance constraint implies it. Here the conformance
# is gated on `n >= 0` but the member requires `n >= 10`, which is not implied,
# so the constrained member type cannot satisfy the trait's plain `Int`
# requirement.
# expected-note @below {{trait 'CondAliasNotImplied' declared here}}
trait CondAliasNotImplied:
# expected-note-re @below {{comptime member 'SIZE' type{{.*}}does not conform to trait's required type 'Int'}}
comptime SIZE: Int
# expected-error @below {{'CondAliasNotImpliedStruct[n]' does not implement all requirements for 'CondAliasNotImplied'}}
struct CondAliasNotImpliedStruct[n: Int = -1](CondAliasNotImplied where n >= 0, Movable where False):
comptime SIZE: Int where Self.n >= 10 = Self.n
# ===========================================================================
# constrained comptime member referenced as result type in an unprovable env
# ===========================================================================
trait Moco4214Op:
comptime Output: AnyType
def operate(self) -> Self.Output:
...
@fieldwise_init
struct Moco4214List[T: AnyType](
Moco4214Op where conforms_to(T, Movable), Movable where False,
):
# expected-note @below {{constraint declared here needs evidence}}
comptime Output: AnyType where conforms_to(Self.T, Movable) = Int
# expected-error @below {{invalid bindings in signature: lacking evidence to prove correctness}}
# expected-note @below {{add a trailing 'where' clause}}
def operate(self) -> Self.Output:
return Int(123)
@@ -0,0 +1,208 @@
# ===----------------------------------------------------------------------=== #
# 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 -split-input-file %s
# @expected-note @below {{extension already assumes these parameter declarations}}
struct Spaceship[T: AnyType]:
pass
# @expected-error @below {{cannot specify parameter declarations on extensions}}
__extension Spaceship[T: AnyType]:
pass
# // -----
# @expected-note @below {{conflicts with this previous declaration}}
def Spaceship():
pass
# @expected-error @below {{cannot define a struct here with name 'Spaceship'}}
struct Spaceship:
pass
# // -----
# @expected-error @below {{can't find a struct named 'Spaceship'}}
__extension Spaceship:
pass
# // -----
# Ambiguous Lookup Case for Two Structs Via One Extension (ALCFTSVOE):
# This is a case where we accidentally reference multiple structs, and one of
# them is accessed via an extension.
# @expected-note @below {{conflicts with this previous struct declaration}}
struct Spaceship:
var fuel: Int
# @expected-error @below {{invalid redefinition of 'Spaceship'}}
struct Spaceship:
pass
__extension Spaceship:
pass
def foo(ship: Spaceship) -> Int: # shouldn't crash here
return ship.fuel # shouldn't crash here either
# // -----
struct ExtensionWhereTarget(Movable where False):
pass
# @expected-error @below {{'where' clauses in conformance lists are only supported on structs}}
__extension ExtensionWhereTarget(AnyType where True):
pass
# // -----
# Tests we can call a constructor defined in an extension.
# CHECK-LABEL: lit.struct.decl @PlainStruct
struct PlainStruct(Movable where False):
pass
# CHECK-LABEL: lit.extension.decl @"extension:PlainStruct"
# CHECK-SAME: targetStruct = @struct_extensions::@PlainStruct
__extension PlainStruct:
# CHECK-LABEL: lit.fn @"__init__
def __init__(out self):
pass
# CHECK-LABEL: lit.fn @"zork
def zork():
# CHECK: lit.call {{.*}}@"__init__
var z = PlainStruct()
# // -----
# Test when an extension method collides with a variable in the struct.
struct BaseStruct:
# expected-note @below {{extension method conflicts with struct declaration}}
var colliding: Int
__extension BaseStruct:
# expected-error @below {{invalid redefinition of 'colliding'}}
def colliding(self) -> Int:
return self.colliding
def test_collisions(s: BaseStruct):
var result = s.colliding()
# // -----
# Test when an extension method collides with an alias in the struct.
struct BaseStruct:
# expected-note @below {{extension method conflicts with struct declaration}}
comptime colliding: Int = 42
__extension BaseStruct:
# expected-error @below {{invalid redefinition of 'colliding'}}
def colliding(self) -> Int:
return self.colliding
def test_collisions(s: BaseStruct):
var result = s.colliding()
# // -----
# Test when an extension alias collides with an alias in the struct.
struct BaseStruct:
# expected-note @below {{extension declaration conflicts with struct declaration}}
comptime colliding: Int = 42
__extension BaseStruct:
# expected-error @below {{invalid redefinition of 'colliding'}}
comptime colliding: Int = 43
def test_collisions(s: BaseStruct):
var result = s.colliding
# // -----
# Test a collision when the extension comes before the struct it extends.
__extension BaseStruct:
# expected-error @below {{invalid redefinition of 'colliding'}}
comptime colliding: Int = 43
struct BaseStruct:
# expected-note @below {{extension declaration conflicts with struct declaration}}
comptime colliding: Int = 42
# // -----
# Test a collision when a use resolves the extension before the struct.
def test_collisions() -> Int:
return BaseStruct.colliding
__extension BaseStruct:
# expected-error @below {{invalid redefinition of 'colliding'}}
comptime colliding: Int = 43
struct BaseStruct:
# expected-note @below {{extension declaration conflicts with struct declaration}}
comptime colliding: Int = 42
# TODO(MOCO-522): Add a test for a function and an extension having same name.
@@ -0,0 +1,27 @@
# ===----------------------------------------------------------------------=== #
# 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 --mojo-disable-builtins -I %S/inputs %s -mlir-print-debuginfo -split-input-file -verify-diagnostics
# @expected-note @below {{conflicts with this previous declaration}}
from struct_package_for_conflict import PlainStruct
# @expected-error @below {{cannot define a struct here with name 'PlainStruct'}}
struct PlainStruct:
pass
__extension PlainStruct:
def sparklebark(self: PlainStruct):
pass
@@ -0,0 +1,39 @@
# ===----------------------------------------------------------------------=== #
# 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 -I %S/inputs -verify-diagnostics %s
# Extensions apply only to the struct decl they were declared on, not to any
# struct that shares its name. `ext_ident_x` and `ext_ident_y` each define
# their own `Foo` plus an extension of it; the explicit import below makes
# `ext_ident_y`'s `Foo` the visible one, while both extensions sit in scope
# under the name key "extension:Foo". Member lookup must only apply the
# extension whose resolved target is the visible `Foo`. Previously the other
# module's static resolved silently to a function of the wrong struct, and its
# instance method died in self-unification with "cannot be converted from
# 'Foo' to 'Foo'" instead of a missing-attribute error.
#
# See MOCO-4406.
from ext_ident_x import *
from ext_ident_y import Foo
def main():
var f = Foo()
_ = f.y_inst()
_ = Foo.y_static()
# expected-error @+1 {{'Foo' value has no attribute 'x_inst'}}
_ = f.x_inst()
# expected-error @+1 {{'Foo' value has no attribute 'x_static'}}
_ = Foo.x_static()
@@ -0,0 +1,341 @@
# ===----------------------------------------------------------------------=== #
# 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 --kgen-print-inline-type-values -verify-diagnostics | FileCheck %s
# ===----------------------------------------------------------------------=== #
# Support types
# ===----------------------------------------------------------------------=== #
trait RPTTrait(TrivialRegisterPassable):
pass
# ===----------------------------------------------------------------------=== #
# Destructor tests
# ===----------------------------------------------------------------------=== #
# CHECK-LABEL: lit.struct.decl @DtorExample1
# Trivial destructor because it's trivial and not explicit.
# CHECK: kgen.witness "__del__is_trivial" : !Bool = {:scalar<bool> true}
struct DtorExample1(AnyType, TrivialRegisterPassable):
var a: Int
# CHECK-LABEL: lit.struct.decl @DtorExample2
# Non-trivial destructor because it is explicit.
# CHECK: kgen.witness "__del__is_trivial" : !Bool = {:scalar<bool> false}
struct DtorExample2(AnyType, RegisterPassable):
var a: Int
def __deinit__(deinit self):
pass
# CHECK-LABEL: lit.struct.decl @DtorExample3
# Trivial destructor RPT is obviously trivial
# CHECK: kgen.witness "__del__is_trivial" : !Bool = {:scalar<bool> true}
struct DtorExample3[T: RPTTrait](Movable where False):
var thing: Self.T
# CHECK-LABEL: lit.struct.decl @DtorExample4
# Dtor is trivial if T's dtor is trivial.
# CHECK: lit.alias.decl __del__is_trivial:
# CHECK-SAME: <#kgen.get_witness<:!AnyType_Deinitable T, {{.*}}"__del__is_trivial">>
# expected-warning @below {{redundant trait composition: 'Deinitable' already implies 'AnyType}}
struct DtorExample4[T: AnyType & Deinitable](Movable where False):
var thing: Self.T
# ===----------------------------------------------------------------------=== #
# Copy/Move synthesis tests
# ===----------------------------------------------------------------------=== #
struct IntPair(ImplicitlyCopyable):
var x: Int
var y: Int
struct IntPairWrapper(ImplicitlyCopyable):
var value: IntPair
# CHECK-LABEL: lit.struct.decl @IntPairWrapper
# CHECK-LABEL: lit.fn @"copy
# CHECK-SAME: (%self: !lit.ref<!IntPairWrapper{{.*}}> imm_mem,
# CHECK-SAME: %__result__: !lit.ref<!IntPairWrapper{{.*}}> byref_result)
# CHECK-NEXT: lit.call {{.*}}@Copyable::@"copy($0){{.*}}(%self, %__result__)
# CHECK-LABEL: lit.fn @"testCopyMoveSynth
def testCopyMoveSynth(var a: IntPair, var b: IntPairWrapper):
# CHECK: lit.memcpy %a, %aCopy
var aCopy = a
# CHECK: lit.call {{.*}}IntPair::@"__init__{{.*}}"{{.*}}({{.*}}, %aMove){{.*}}*, "move"
var aMove = a^
# CHECK: lit.call {{.*}}IntPair::@"copy{{.*}}({{.*}}, %aExCopy)
var aExCopy = a.copy()
# CHECK: lit.memcpy %b, %bCopy
var bCopy = b
# CHECK: lit.call {{.*}}IntPairWrapper::@"__init__{{.*}}"{{.*}}({{.*}}, %bMove){{.*}}*, "move"
var bMove = b^
# CHECK: lit.call {{.*}}IntPairWrapper::@"copy{{.*}}({{.*}}, %bExCopy)
var bExCopy = b.copy()
struct IntPairNT(ImplicitlyCopyable):
var x: Int
var y: Int
comptime __copy_ctor_is_trivial = False
struct IntPairWrapperNT(ImplicitlyCopyable):
var value: IntPairNT
# CHECK-LABEL: lit.fn @"testCopyMoveSynthNonTrivial
def testCopyMoveSynthNonTrivial(var a: IntPairNT, var b: IntPairWrapperNT):
# CHECK: lit.call {{.*}}IntPairNT::@"__init__{{.*}}"{{.*}}({{.*}}, %aCopy){{.*}}*, "copy"
var aCopy = a
# CHECK: lit.call {{.*}}IntPairNT::@"__init__{{.*}}"{{.*}}({{.*}}, %aMove){{.*}}*, "move"
var aMove = a^
# CHECK: lit.call {{.*}}IntPairNT::@"copy{{.*}}({{.*}}, %aExCopy)
var aExCopy = a.copy()
# CHECK: lit.call {{.*}}IntPairWrapperNT::@"__init__{{.*}}"{{.*}}({{.*}}, %bCopy){{.*}}*, "copy"
var bCopy = b
# CHECK: lit.call {{.*}}IntPairWrapperNT::@"__init__{{.*}}"{{.*}}({{.*}}, %bMove){{.*}}*, "move"
var bMove = b^
# CHECK: lit.call {{.*}}IntPairWrapperNT::@"copy{{.*}}({{.*}}, %bExCopy)
var bExCopy = b.copy()
# ===----------------------------------------------------------------------=== #
# Fieldwise init tests
# ===----------------------------------------------------------------------=== #
@fieldwise_init
struct FieldwiseInitExample1[T: Movable & Deinitable](Movable where False):
var x: Int
var y: Self.T
# CHECK-LABEL: lit.struct.decl @FieldwiseInitExample1
# CHECK: lit.fn @"__init__(::SIMD
# CHECK-SAME: (%x: !alias_Int1, %y: !lit.ref<:!AnyType_Deinitable_Movable T, mut *"y`"> owned_in_mem,
# CHECK-SAME: %self: !lit.ref<{{.*}}> byref_result)
# CHECK-NEXT: [[TMP:%.*]] = lit.ref.struct.ger %self[x]
# CHECK-NEXT: lit.ref.store %x, [[TMP]]
# CHECK-NEXT: [[TMP:%.*]] = lit.ref.struct.ger %self[y]
# CHECK-NEXT: lit.call{{.*}}"__init__(move:$0$)">{{.*}}(%y, [[TMP]])
# CHECK-NEXT: %none = kgen.param.constant: none = <#kgen.none>
# CHECK-LABEL: lit.struct.decl @FieldwiseInitExample2
@fieldwise_init("implicit")
struct FieldwiseInitExample2(Movable where False):
var x: Int
# CHECK-LABEL: lit.fn @"testFieldwiseInitExample2
# CHECK: FieldwiseInitExample2::@"__init__{{.*}}(%0, %b)
def testFieldwiseInitExample2(a: Int):
var b: FieldwiseInitExample2 = a
# Register passable example.
# CHECK-LABEL: lit.struct.decl @FieldwiseInitExample3
@fieldwise_init("implicit")
struct FieldwiseInitExample3(RegisterPassable):
var x: Int
# ===----------------------------------------------------------------------=== #
# Shadow auto-parameterized parameters
# ===----------------------------------------------------------------------=== #
struct MyParam[p: Int](Movable where False):
pass
trait TraitWithPAlias:
comptime p: Int = 42
# CHECK-LABEL: lit.struct.decl @MyStruct
# CHECK-SAME: <[{{.*}}]*"[[P1:.*]]": !Int, [{{.*}}]*"[[P2:.*]]": !Int, +, p: !Int,
# CHECK-SAME: m1: !lit.struct<#MyParam <:!Int *"[[P1]]">>, m2: !lit.struct<#MyParam <:!Int *"[[P2]]">>
struct MyStruct[p: Int, m1: MyParam[_], m2: MyParam[_]](Movable where False):
# CHECK: lit.fn @"__init__()"[
def __init__(out self):
pass
# CHECK-LABEL: lit.struct.decl @MyStructWithPVar
struct MyStructWithPVar[m1: MyParam[_]](Movable where False):
def __init__(out self):
pass
# COM: Ensure there's no conflict with this var.
var p: Int
# CHECK-LABEL: lit.struct.decl @MyStructWithPAlias
struct MyStructWithPAlias[m1: MyParam[_]](Movable where False):
def __init__(out self):
pass
# COM: Ensure there's no conflict with this alias.
comptime p: Int = 2
# CHECK-LABEL: lit.struct.decl @MyStructWithTraitWithPAlias
struct MyStructWithTraitWithPAlias[m1: MyParam[_]](TraitWithPAlias, Movable where False):
# COM: Ensure there's no conflict with the inherited alias.
def __init__(out self):
pass
# CHECK-LABEL: lit.struct.decl @MyStructWithPFunc
struct MyStructWithPFunc[m1: MyParam[_]](Movable where False):
def __init__(out self):
pass
# COM: Ensure there's no conflict with this method (single definition).
def p(self, x: Int):
pass
# CHECK-LABEL: lit.struct.decl @MyStructWith2PFuncs
struct MyStructWith2PFuncs[m1: MyParam[_]](Movable where False):
def __init__(out self):
pass
# COM: Ensure there's no conflict with this method (multiple definitions).
def p(self):
pass
def p(self, x: Int):
pass
# ===----------------------------------------------------------------------=== #
# Nonmaterializable
# ===----------------------------------------------------------------------=== #
@fieldwise_init("implicit")
struct NmTarget(TrivialRegisterPassable):
var x: Bool
@always_inline("builtin")
@implicit
def __init__(out self, nms: NmStruct):
self.x = True if (nms.x == 77) else False
def __bool__(self) -> Bool:
return self.x
@__nonmaterializable(NmTarget)
struct NmStruct(TrivialRegisterPassable):
var x: Int
@always_inline("builtin")
@implicit
def __init__(out self, x: Int):
self.x = x
@always_inline("builtin")
def __add__(self, rhs: Self) -> Self:
return NmStruct(self.x + rhs.x)
# CHECK: lit.alias.decl{{.*}}notMaterializedAlias{{.*}}NmStruct{{.*}}77
comptime notMaterializedAlias = NmStruct(77)
# CHECK: lit.alias.decl{{.*}}notMaterializedButConverted{{.*}}: !NmTarget = {{.*}}{:scalar<bool> false}})>
comptime notMaterializedButConverted: NmTarget = NmStruct(76)
def tail_types[T: AnyType, *U: AnyType](a: T, *b: *U):
pass
def nmTargetNoop(x: NmTarget):
pass
def explicit_non_nm_target[T: NmStruct]():
pass
def nmResult() -> NmStruct:
pass
# CHECK-LABEL: lit.fn @"useNonmaterializable
def useNonmaterializable(p: Bool):
# CHECK: lit.var.decl "gotConverted1" var : !lit.ref<!NmTarget
# CHECK: kgen.param.constant: !NmTarget {{.*}}{:scalar<bool> true}
var gotConverted1 = NmStruct(76) + NmStruct(1)
# CHECK: lit.var.decl "gotConverted2" var : !lit.ref<!NmTarget
# CHECK: kgen.param.constant: !NmTarget {{.*}}{:scalar<bool> false}
var gotConverted2 = notMaterializedAlias + NmStruct(1)
# CHECK: lit.alias.decl{{.*}}useIfAlias{{.*}}NmStruct{{.*}}2
comptime useIfAlias = NmStruct(2) if True else NmStruct(3)
# CHECK: lit.var.decl "useIfVar" var : !lit.ref<!NmTarget
var useIfVar = NmStruct(2) if p else NmStruct(77)
# CHECK: lit.var.decl "useIfVarLopsided" var : !lit.ref<!NmTarget
var useIfVarLopsided = NmTarget(False) if not p else NmStruct(77)
# CHECK: lit.var.decl "useOrVar1" var : !lit.ref<!NmTarget
var useOrVar1 = NmStruct(2) or NmStruct(77)
# CHECK: lit.var.decl "useOrVar2" var : !lit.ref<!NmTarget
var useOrVar2 = NmStruct(2) or NmStruct(3)
# CHECK: lit.var.decl "useAndVar1" var : !lit.ref<!NmTarget
var useAndVar1 = NmStruct(2) and NmStruct(77)
# CHECK: lit.var.decl "useAndVar2" var : !lit.ref<!NmTarget
var useAndVar2 = NmStruct(77) and NmStruct(77)
# Test that parameter inference using nonmaterializable gives the target,
# not the nonmaterializable type.
# CHECK: lit.call {{.*}}tail_types{{.*}}<:param_list<!AnyType> [], :!AnyType !NmTarget,
tail_types(NmStruct(5))
# CHECK: lit.call {{.*}}tail_types{{.*}}<:param_list<!AnyType> [!NmTarget], :!AnyType !NmTarget,
tail_types(NmStruct(5), NmStruct(6))
# However, if the type is the explicitly not the nm-target, it should also work
# CHECK: call {{.*}}explicit_non_nm_target{{.*}}<:!NmStruct {{.*}}>
explicit_non_nm_target[NmStruct(5)]()
# CHECK-NEXT: [[TMP:%.*]] = lit.call {{.*}}nmResult{{.*}}()
# CHECK: %nmResult = lit.var.decl
# CHECK-NEXT: [[TMP2:%.*]] = lit.call {{.*}}NmTarget::@"__init__{{.*}}([[TMP]])
# CHECK-NEXT: lit.ref.store [[TMP2]], %nmResult
var nmResult = nmResult()
@@ -0,0 +1,72 @@
# ===----------------------------------------------------------------------=== #
# 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
trait Trait1:
def f1(self):
...
trait Trait2:
def f2(self):
...
trait Trait3:
def f3(self):
...
comptime Traits12 = Trait1 & Trait2
comptime Traits23 = Trait2 & Trait3
comptime Traits123 = Trait1 & Trait2 & Trait3
@fieldwise_init
struct Struct4(Movable where False):
def f4(self):
pass
# expected-note @below {{function declared here}}
def use1[T: Trait1](x: T):
pass
# Use aliased trait composition.
# expected-note @below {{function declared here}}
def use12Alias[T: Traits12](x: T):
pass
# Use direct trait composition.
# expected-note @below {{function declared here}}
def use12Direct[T: Trait1 & Trait2](x: T):
pass
# CHECK: lit.fn @"main_use()"
def main_use():
var s4 = Struct4()
# expected-error @below {{invalid call to 'use1': value passed to 'x' cannot be converted from 'Struct4' to 'T', argument type 'Struct4' does not conform to trait 'Trait1'}}
use1(s4)
# expected-error @below {{invalid call to 'use12Alias': value passed to 'x' cannot be converted from 'Struct4' to 'T', argument type 'Struct4' does not conform to trait 'Traits12'}}
# expected-note @below {{'Traits12' is aka 'Trait1 & Trait2'}}
use12Alias(s4)
# expected-error @below {{invalid call to 'use12Direct': value passed to 'x' cannot be converted from 'Struct4' to 'T', argument type 'Struct4' does not conform to trait 'Trait1 & Trait2'}}
use12Direct(s4)
@@ -0,0 +1,362 @@
# ===----------------------------------------------------------------------=== #
# 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
# expected-note @below {{trait 'MyMovable' declared here}}
trait MyMovable:
# expected-note @below {{required function '__init__' is not implemented}}
def __init__(out self, *, deinit move: Self):
...
trait ErroneousTrait:
# expected-error @+2 {{'self' argument must have type 'Self' in trait method declaration, but actually has type 'Int'}}
@__allow_legacy_custom_self_type
def add(self: Int):
...
trait FooTrait:
def foo(self):
...
# expected-error @below {{'where' clauses in conformance lists are only supported on structs}}
trait WhereClauseInTraitConformanceList(FooTrait where True):
pass
struct ParamType[x: Int](FooTrait, Movable where False):
def foo(self):
pass
def invalid_trait_bind():
# expected-error @below {{'ParamType[_]' is not concrete, use '[]' to bind missing parameters}}
comptime Bound: FooTrait = ParamType
def different_trait_types[
T: ImplicitlyCopyable, U: ImplicitlyCopyable
](x: T) -> U:
# expected-error @below {{cannot implicitly convert 'T' value to 'U'}}
return x
# expected-note @below {{trait 'SimpleTrait' declared here}}
trait SimpleTrait:
# expected-note @below {{required function 'some_method' is not implemented}}
# expected-note @below {{no 'some_method' candidates have type 'def(self: ParamDoesNotConform[x]) thin -> None'}}
def some_method(self):
...
# expected-error @below {{'TraitStruct' does not implement all requirements for 'MyMovable'}}
struct TraitStruct(MyMovable, SimpleTrait, Movable where False):
def some_method(self):
pass
# expected-note @+1 {{function declared here}}
def test_many_things_of_specified_trait[
element_type: type_of(AnyType), //, *element_types: element_type
]():
pass
# expected-error @below {{'DoesNotConform' does not implement all requirements for 'SimpleTrait'}}
struct DoesNotConform(SimpleTrait, Movable where False):
pass
# expected-error @below {{'ParamDoesNotConform[x]' does not implement all requirements for 'SimpleTrait'}}
struct ParamDoesNotConform[x: Int](SimpleTrait, Movable where False):
# expected-note @below {{candidate declared here with type 'def(self: ParamDoesNotConform[x], y: Int) thin -> None' (specialized from 'def[x: Int, //](self: ParamDoesNotConform[x], y: Int) thin -> None')}}
def some_method(self, y: Int):
pass
def call_many_things_of_specified_trait(a: TraitStruct):
# This is ok!
test_many_things_of_specified_trait[
element_type=AnyType, TraitStruct, Int
]()
# expected-error @+2 {{'test_many_things_of_specified_trait' parameter 'element_types' has 'Movable' type, but value has type 'AnyStruct[TraitStruct]'}}
test_many_things_of_specified_trait[
element_type=Movable, TraitStruct, TraitStruct
]()
test_many_things_of_specified_trait[
element_type=SimpleTrait,
TraitStruct,
# This will succeed, the error will be raised when resolving `DoesNotConform`.
DoesNotConform,
]()
# expected-note@+1 {{trait 'TrivialTrait' declared here}}
trait TrivialTrait(TrivialRegisterPassable):
# expected-note@+1 {{required function 'doSomething' is not implemented}}
def doSomething(self):
...
# expected-note@+1 {{inherited through 'MemTraitViolation' here}}
trait MemTraitViolation(TrivialTrait):
def bar(self):
...
trait NonTrivialRGTrait(RegisterPassable):
def bar(self):
...
# expected-error @+1 {{does not implement all requirements for}}
struct StructViolation2(TrivialTrait):
pass
# expected-error @+1 {{does not implement all requirements for}}
struct StructViolation3(MemTraitViolation):
def bar(self):
pass
trait NotDeinitable:
def foo(self):
...
@fieldwise_init
struct Bar[T: NotDeinitable](Movable where False): # expected-note {{'Bar' declared here}}
pass
def bindAnyTraitToTrait():
# expected-error @+1 {{'Bar' parameter 'T' has 'NotDeinitable' type, but value has type 'AnyTrait[NotDeinitable]'}}
var _list = Bar[NotDeinitable]()
def anytrait_assignment():
# expected-error @below {{cannot implicitly convert 'AnyTrait[ImplicitlyCopyable]' value to 'AnyTrait[FooTrait]' in comptime initializer}}
comptime t: type_of(FooTrait) = ImplicitlyCopyable
trait SomeTrait:
comptime A: Int
@fieldwise_init
struct TakeInt[A: Int](Movable where False):
pass
# expected-note @below {{function declared here}}
def take_two_inferred_params[Size: Int](x: TakeInt[Size], y: TakeInt[Size]):
pass
def call_take_two_inferred_params[T: SomeTrait](x: T):
# expected-error @below {{invalid call to 'take_two_inferred_params': value passed to 'y' cannot be converted from 'TakeInt[Int(1)]' to 'TakeInt[T.A]'}}
take_two_inferred_params(TakeInt[T.A](), TakeInt[1]())
# Check that a trait method with a default implementation returning a non-None
# type may not use 'pass'.
trait TBar:
# expected-error @+4 {{trait method with a return type must not use 'pass'; use '...' to declare the method as required}}
# expected-note @below {{in 'bar', declared here}}
# expected-note @below {{original default implementation from trait 'TBar' here}}
def bar(self) -> Int:
pass
trait TBarSub(TBar):
# expected-note @below {{conflicting implementation from trait 'TBarSub' here}}
def bar(self) -> Int:
return 0
# expected-error @+1 {{trait method requirement 'bar' has conflicting default implementations in 'TBar' and 'TBarSub'; you must implement it manually}}
struct TBarActual(TBarSub, Movable where False):
pass
trait WhereClauseOnTraitMethod:
# expected-error @+1 {{'where' clauses on trait methods are not supported}}
def guarded_method(self) where Self.x > 10:
pass
trait ConflictTraitName:
# expected-note @+1 {{trait method declared here}}
def test[a: Int](self):
pass
# expected-error @+1 {{name conflict between parameter 'a' in the default trait method and a parameter in the struct}}
struct ConflictStruct[a: Int](ConflictTraitName, Movable where False):
pass
# ===----------------------------------------------------------------------=== #
# Synthesized __deinit__
# ===----------------------------------------------------------------------=== #
# MOCO-4252
struct CondDeletableField1[T: AnyType](
Deinitable where conforms_to(T, Deinitable), Movable where False,
):
var value: Self.T # Ok
struct CondDeletableField2[T: AnyType, X: Int](
Deinitable where conforms_to(T, Deinitable) and X > 10, Movable where False,
):
var value: Self.T # Ok
struct CondDeletableField3[T: AnyType, X: Int](
Deinitable where X > 10, Movable where False,
):
var value: Self.T # expected-error {{field 'value' has non-'Deinitable' type 'T'}}
# MOCO-4262
struct NeverDeletableInner(Deinitable where False, Movable where False):
pass
struct NeverDeletableOuter(Deinitable where False, Movable where False):
var m: NeverDeletableInner
# MOCO-4332: same opt-out idiom as MOCO-4262 above, but for Movable/Copyable.
# A struct whose own move/copy-ctor synthesis is doomed by `where False` must
# not require its fields to conform to Movable/Copyable either, even when the
# field's own conformance is *also* a doomed `where False`.
struct NeverMovableInner(Movable where False):
pass
struct NeverMovableOuter(Movable where False):
var m: NeverMovableInner
struct NeverCopyableInner(Copyable where False):
pass
struct NeverCopyableOuter(Copyable where False):
var m: NeverCopyableInner
# The `not` spelling of the same two shapes. Field conformance is checked
# through a different route than synthesis gating (`ASTType::isMovable` rather
# than `getConformanceCondition`), so the composed cases are worth pinning for
# both spellings.
struct NotDeletableInner(not Deinitable, not Movable):
pass
struct NotDeletableOuter(not Deinitable, not Movable):
var m: NotDeletableInner
struct NotMovableInner(not Movable):
pass
struct NotMovableOuter(not Movable):
var m: NotMovableInner
# Field-movability is irrelevant once the outer struct opts out: because a
# `Movable where False` struct synthesizes no move constructor, its fields are
# never checked for movability. Both a movable field and a wholly non-movable
# one must therefore compile without any field-focused diagnostic.
struct UnconditionallyMovableField(Movable):
pass
struct NeverMovableOuterWithMovableField(Movable where False):
var m: UnconditionallyMovableField
struct NotMovableAtAll:
pass
struct NeverMovableOuterWithNonMovableField(Movable where False):
var m: NotMovableAtAll
# ===----------------------------------------------------------------------=== #
# Synthesized functions with unsatisfiable where clauses
# ===----------------------------------------------------------------------=== #
# MOCO-4303: a `Movable where False` opt-out synthesizes no move constructor,
# so a call that could only resolve to that synthesized candidate finds no
# candidates at all rather than being "explained" against a never-callable one.
struct NeverMovable[T: AnyType](Movable where False):
pass
def never_movable_call_is_no_candidates_found():
# expected-error @+1 {{invalid call to '__init__': no candidates found}}
var z = NeverMovable[Int]()
struct NeverCopyable(Movable, Copyable where False):
var v: Int
def __init__(out self, v: Int):
self.v = v
def never_copyable_call_is_no_candidates_found():
var a = NeverCopyable(1)
# A `Copyable where False` opt-out synthesizes no copy constructor, so
# `copy` is not a member at all.
# expected-error @+1 {{'NeverCopyable' value has no attribute 'copy'}}
var b = a.copy()
# Same as above, but exercised through a user-defined trait with a defaulted
# method (synthesizeDefaultTraitMethodWrapper) instead of a builtin special
# member (Movable/Copyable/Deinitable). Confirms the fix isn't
# specific to compiler-synthesized special members.
trait Greeter:
def greet(self, name: String) -> String:
return "Hello, " + name
struct SilentGreeter(Greeter where False, Movable where False):
var x: Int
def __init__(out self, x: Int):
self.x = x
def never_greeter_call_is_no_candidates_found():
var s = SilentGreeter(1)
# A `Greeter where False` opt-out synthesizes no default-method wrapper, so
# `greet` is not a member at all.
# expected-error @+1 {{'SilentGreeter' value has no attribute 'greet'}}
var msg = s.greet()
@@ -0,0 +1,69 @@
# ===----------------------------------------------------------------------=== #
# 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
# Near-miss suggestions for unknown declarations via edit distance.
def use(x: Int):
pass
def local_typo():
var count = 1
# expected-error @+1 {{use of unknown declaration 'coun'; did you mean 'count'?}}
use(coun)
def param_typo(value: Int):
# expected-error @+1 {{use of unknown declaration 'valu'; did you mean 'value'?}}
use(valu)
def outer_scope_typo():
var module_level = 7
def inner():
# expected-error @+1 {{use of unknown declaration 'module_leve'; did you mean 'module_level'?}}
use(module_leve)
inner()
# No suggestion when nothing in scope is close enough.
def no_near_miss():
# expected-error @+1 {{use of unknown declaration 'zzzzz'}}
use(zzzzz)
# Short names are not suggested against each other.
def short_name(x: Int):
# expected-error @+1 {{use of unknown declaration 'y'}}
use(y)
# Tied nearest neighbors suppress the suggestion rather than guessing.
def ambiguous_tie():
var fooa = 1
var foob = 2
# expected-error @+1 {{use of unknown declaration 'foox'}}
use(foox)
use(fooa)
use(foob)
# Hardcoded rename still wins over a coincidental near miss.
def type_of_rename(type_of_x: Int):
# expected-error @+1 {{use of unknown declaration 'typeof'; did you mean 'type_of'?}}
_ = typeof
+163
View File
@@ -0,0 +1,163 @@
# ===----------------------------------------------------------------------=== #
# 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
struct MemExample(Movable where False):
pass
def return_generic_memory_only[T: AnyType]() -> T:
pass
def fudge_int(x: Int) -> Int:
return x
# CHECK-LABEL: lit.fn @"var_decls()
def var_decls():
# CHECK: %y = lit.var.decl "y" var
var y: Int
# CHECK: %[[Y:.*]] = lit.ref.load %{{.*}}
# CHECK: %[[F:.*]] = lit.call {{.*}}::@"fudge_int{{.*}}(%[[Y]])
# CHECK: lit.ref.store %[[F]], %y
y = fudge_int(y)
# CHECK: %z = lit.var.decl {{.*}} : !lit.ref<:meta<!Int> #alias_Int,
# CHECK-NEXT: [[TMP:%.*]] = lit.ref.load %y
# CHECK-NEXT: lit.ref.store [[TMP]], %z
var z = y
z = 42
# CHECK-NEXT: [[TMP:%.*]] = kgen.param.constant: !alias_Int1 = <rebind(:!Int {:scalar<index> 42})>
# CHECK-NEXT: lit.ref.store [[TMP]], %z
# CHECK-LABEL: lit.fn @"test_var_let_scopes
def test_var_let_scopes(cond: Bool):
# CHECK: lit.var.decl "c"
# CHECK: hlcf.if
var c = 10
if cond:
# CHECK: lit.var.decl "c"
var c = 42
# CHECK: else
else:
# CHECK: lit.var.decl "c"
var c = 123
# CHECK-LABEL: lit.fn @"test_var_origin_mangling
def test_var_origin_mangling[x: Int](c: Bool):
# CHECK: hlcf.if
if c:
# CHECK: lit.var.decl "y" var : !lit.ref<!Int, mut *"y`">
var y = x
# CHECK: } else {
else:
# CHECK: lit.var.decl "y" var : !lit.ref<!Int, mut *"y`1">
var y = x
# CHECK-LABEL: lit.fn @"test_nested_var_origin_mangling
def test_nested_var_origin_mangling[x: Int](c: Bool):
# CHECK: hlcf.if
if c:
# CHECK: lit.var.decl "y" var : !lit.ref<!Int, mut *"y`">
var y = x
# CHECK: lit.fn *"nested()"
def nested() capturing:
# CHECK: lit.var.decl "y" var : !lit.ref<!Int, mut *"y`2x">
var y = x
# Issue #18157 and issue #18158, shadowing variables should be able to reference
# the shadowed variable on the RHS.
def test_shadowing_reference_shadowed(cond: Bool):
var num: Int = 10
if cond:
var num = fudge_int(42)
# ===----------------------------------------------------------------------=== #
# Explicitly declared mutable variables used across control flow.
# ===----------------------------------------------------------------------=== #
# CHECK-LABEL: lit.fn @"var_decls_mutable()
def var_decls_mutable() raises -> None:
# CHECK: %x = lit.var.decl "x" var
var x = 123
# CHECK: [[TMP:%.*]] = kgen.param.constant: !Int = <{:scalar<index> 42}>
# CHECK: [[F:%.*]] = lit.call {{.*}}::@"fudge_int{{.*}}([[TMP]])
# CHECK: lit.ref.store [[F]], %x
x = fudge_int(42)
def use_int(x: Int):
pass
# Check values are declared at top level where they belong.
# https://github.com/modularml/modular/issues/34368
# CHECK-LABEL: lit.fn @"walrus_control_flow
def walrus_control_flow(a: Int) raises:
# CHECK: %curr = lit.var.decl "curr"
# CHECK: %b = lit.var.decl "b"
var curr = a
var b: Int
# CHECK: lit.loop {
# CHECK-NEXT: lit.ref.load %curr
while b := curr + 1:
# lit.loop.break.else
# CHECK: lit.ref.load
# CHECK: use_int
use_int(b)
curr = b
# CHECK-LABEL: lit.fn @"addrSpaces
def addrSpaces[lt1: MutOrigin, lt2: ImmOrigin, as1: AddressSpace]():
# CHECK: lit.var.decl "ref1" {{.*}}!lit.ref<!MemExample, mut {{.*}}lt1{{.*}}, #lit.struct.extract<:!SIMDLength #lit.struct.extract<:!AddressSpace as1, "_value">, "_mlir_value">>
var ref1: Pointer[MemExample, lt1, address_space=as1]._mlir_lit_ref
# CHECK: lit.alias.decl [[AS2:.*]]: !AddressSpace = {{.*}} {42}
comptime as2: AddressSpace = AddressSpace(42)
# CHECK: lit.var.decl "ref2" {{.*}}!lit.ref<!MemExample, imm *"lt2._mlir_origin`1", 42>, mut
var ref2: __mlir_type[
`!lit.ref<`,
MemExample,
`, `,
lt2._mlir_origin,
`, `,
+as2._value._mlir_value,
`>`,
]
# https://github.com/modular/modular/issues/4765
def redundant_var_ref():
var n = 1
# expected-warning @+1 {{nested 'var' or 'ref' patterns are redundant, remove the outer pattern}}
var ref a = n
# https://github.com/modular/modular/issues/6700
# expected-warning @+1 {{nested 'var' or 'ref' patterns are redundant, remove the outer pattern}}
ref var y : Int = n
@@ -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
struct SomeStruct(Movable where False):
def __init__(out self): pass
struct SomeOtherStruct(Movable where False): pass
def var_decl_without_type():
# expected-error @+1 {{cannot declare 'x' without a contextual type from its initializer}}
var x
# expected-error @+1 {{invalid implicit conversion to 'SomeOtherStruct': no constructors found}}
var y : SomeOtherStruct = SomeStruct()
# expected-error @+1 {{invalid implicit conversion to 'SomeOtherStruct': no constructors found}}
var z: SomeOtherStruct = SomeStruct()
def fudge_int(x: Int): pass
def var_decl():
var x = "x" # expected-note {{previous definition here}}
var x : Int # expected-error {{invalid redefinition of 'x'}}
fudge_int(x) # No follow-on error.
def bad_type_error_message():
var localVar = 42
var y : localVar # expected-error {{cannot use a dynamic value in type specification}}
var x: Int
var ptr: fudge_int(x) # expected-error {{cannot use a dynamic value in type specification}}
def missing_type_on_var_decl():
var abc : # This line break is intentional.
pass # expected-error {{unexpected token in expression}}
fudge_int(abc) # No follow-on error.
def bad_stmt_list(cond: Bool):
# expected-error @+1 {{'if' statement must be on its own line}}
var abc = 42; if cond: pass
def cannot_fwd_declare_plus_equal():
# expected-error @+1 {{use of unknown declaration 'x'}}
x += 42
def test_var_let_type_literal_value():
# expected-error @below {{expected a type, not a value}}
var c: 42
def use_before_def():
# expected-error @below {{use of unknown declaration 'x'}}
var y = x
var x = 42
# Issue #18150: https://github.com/modularml/modular/issues/18150
def self_reference():
# expected-error @+1 {{cannot implicitly convert 'None' value to 'Int'}}
var num: Int = fudge_int(1)
# Doesn't reject empty identifier name
# https://github.com/modular/mojo/issues/1232
def empty_name():
# expected-error @+1 {{backtick identifier must not be empty; add content between the backticks}}
var `` = 42
# COM: Issue #957 https://github.com/modular/mojo/issues/957
struct MemoryStruct(Movable where False):
@implicit
def __init__(out self, s: Int): pass
def take_variadic(*elements: MemoryStruct): pass
def test_var_let_type_variadic_func():
# expected-error @below {{expected a type, not a value}}
var a: take_variadic(42)
@@ -0,0 +1,125 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
# RUN: %parse-mojo-isolated -verify-diagnostics %s
##===----------------------------------------------------------------------===##
# Tests which callee constraints a caller's where clause proves, disproves, or
# leaves unproven. Each failing call is the control for the case above it: it
# shows the passing call is discharged by its assumption, not skipped.
##===----------------------------------------------------------------------===##
trait A:
pass
trait B:
pass
# expected-note @below {{cannot prove constraint for candidate}}
# expected-note @below {{constraint declared here needs evidence for 'a or b'}}
def needs_either[a: Bool, b: Bool]() where a or b:
pass
def or_weakening[a: Bool, b: Bool]() where a:
needs_either[a, b]()
def or_unproven[a: Bool, b: Bool]():
# expected-error @below {{invalid call to 'needs_either': lacking evidence to prove correctness}}
# expected-note @below {{provide evidence for the constraint here to aid in candidate selection}}
needs_either[a, b]()
# expected-note @below {{cannot prove constraint for candidate}}
# expected-note @below {{constraint declared here needs evidence for 'conforms_to(T, A & B)'}}
def needs_joint[T: AnyType]() where conforms_to(T, A & B):
pass
# COM: Neither bound alone proves the packed one.
def joint_conformance[
T: AnyType
]() where conforms_to(T, A) and conforms_to(T, B):
needs_joint[T]()
def joint_unproven[T: AnyType]() where conforms_to(T, A):
# expected-error @below {{invalid call to 'needs_joint': lacking evidence to prove correctness}}
# expected-note @below {{provide evidence for the constraint here to aid in candidate selection}}
needs_joint[T]()
# expected-note @below {{cannot prove constraint for candidate}}
# expected-note @below {{constraint declared here needs evidence for 'a and b'}}
def needs_both[a: Bool, b: Bool]() where a and b:
pass
# COM: Each conjunct of the goal is already known, so the whole goal is.
def restated_conjunction[a: Bool, b: Bool]() where a and b:
needs_both[a, b]()
def conjunction_unproven[a: Bool, b: Bool]() where a:
# expected-error @below {{invalid call to 'needs_both': lacking evidence to prove correctness}}
# expected-note @below {{provide evidence for the constraint here to aid in candidate selection}}
needs_both[a, b]()
# expected-note @below {{cannot prove constraint for candidate}}
# expected-note @below {{constraint declared here needs evidence for '(N == K)'}}
def needs_equal[N: Int, K: Int]() where N == K:
pass
def restated_equal[N: Int, K: Int]() where N == K:
needs_equal[N, K]()
def equal_unproven[N: Int, K: Int]():
# expected-error @below {{invalid call to 'needs_equal': lacking evidence to prove correctness}}
# expected-note @below {{provide evidence for the constraint here to aid in candidate selection}}
needs_equal[N, K]()
# expected-note @below {{cannot prove constraint for candidate}}
# expected-note @below {{constraint declared here needs evidence for '(N != K)'}}
def needs_not_equal[N: Int, K: Int]() where N != K:
pass
def restated_not_equal[N: Int, K: Int]() where N != K:
needs_not_equal[N, K]()
def not_equal_unproven[N: Int, K: Int]():
# expected-error @below {{invalid call to 'needs_not_equal': lacking evidence to prove correctness}}
# expected-note @below {{provide evidence for the constraint here to aid in candidate selection}}
needs_not_equal[N, K]()
# expected-note @below {{function declared here}}
# expected-note @below {{constraint declared here evaluated to False, expected 'not a'}}
def needs_not[a: Bool]() where not a:
pass
# COM: The assumption contradicts the constraint, which is a harder error than
# COM: the unproven ones above.
def disproved[a: Bool]() where a:
# expected-error @below {{invalid call to 'needs_not': violated constraint}}
needs_not[a]()
@@ -0,0 +1,140 @@
# ===----------------------------------------------------------------------=== #
# 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.
# ===----------------------------------------------------------------------=== #
# A conformance proved by a `where` clause must be honored everywhere, not only
# where type refinement folded it into the parameter's bound. The function result
# type is declared, never refined, so `return x^` used to consult the unrefined
# `T` and report a missing `Movable` conformance while every body-level transfer
# of the same value succeeded.
# RUN: %parse-mojo-isolated -verify-diagnostics %s
##===----------------------------------------------------------------------===##
# The reported shape: transfer out through `return`.
##===----------------------------------------------------------------------===##
def ret_move[T: Deinitable](var x: T) -> T where conforms_to(T, Movable):
return x^
# Via a local, so the transferred value's type comes from the body rather than
# from the signature.
def ret_move_via_local[
T: Deinitable
](var x: T) -> T where conforms_to(T, Movable):
var y = x^
return y^
# `Copyable` refines `Movable`, so it proves the transfer too.
def ret_move_from_copyable[
T: Deinitable
](var x: T) -> T where conforms_to(T, Copyable):
return x^
# Exact shape from the bug report: stacked where-clauses including
# `Deinitable` alongside `Copyable`.
def ret_move_from_copyable_and_deletable[
T: Deinitable
](var x: T) -> T where conforms_to(T, Copyable) where conforms_to(
T, Deinitable
):
return x^
##===----------------------------------------------------------------------===##
# Not specific to `Movable`: the implicit-copy check took the same path.
##===----------------------------------------------------------------------===##
def ret_implicit_copy[
T: Deinitable
](var x: T) -> T where conforms_to(T, ImplicitlyCopyable):
return x
##===----------------------------------------------------------------------===##
# Controls: these already worked through type refinement and must keep working.
##===----------------------------------------------------------------------===##
def sink[U: Deinitable & Movable](var v: U):
pass
def body_move[T: Deinitable](var x: T) where conforms_to(T, Movable):
var y = x^
_ = y^
def move_assign[
T: Deinitable
](var x: T, var y: T) where conforms_to(T, Movable):
y = x^
_ = y^
def transfer_as_argument[T: Deinitable](var x: T) where conforms_to(T, Movable):
sink(x^)
def body_implicit_copy[
T: Deinitable
](var x: T) where conforms_to(T, ImplicitlyCopyable):
var y = x
_ = y^
_ = x^
# An unconditional bound, not an assumption.
def direct_bound[T: Movable](var x: T) -> T:
return x^
##===----------------------------------------------------------------------===##
# Negative guards: a proven-absent conformance must still be an error. These
# catch a fix that promotes every unprovable conformance to "proven".
##===----------------------------------------------------------------------===##
# A concrete type that opts out of `Movable`. The metatype guard must keep
# answering `no` here rather than reaching for the assumptions.
struct NotMovable(Movable where False):
def __init__(out self):
pass
def concrete_not_movable(var m: NotMovable) -> NotMovable:
# expected-error @below {{cannot transfer value into destination, because 'NotMovable' doesn't conform to 'Movable'}}
return m^
# Generic with no assumption at all: still unprovable.
def generic_no_assumption[T: Deinitable](var x: T) -> T:
# expected-error @below {{cannot transfer value into destination, because 'T' doesn't conform to 'Movable'}}
return x^
# An assumption about an unrelated trait must not prove `Movable`.
trait Unrelated:
pass
def wrong_assumption[
T: Deinitable
](var x: T) -> T where conforms_to(T, Unrelated):
# expected-error @below {{cannot transfer value into destination, because 'T' doesn't conform to 'Movable'}}
return x^
@@ -0,0 +1,122 @@
# ===----------------------------------------------------------------------=== #
# 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 a message written `where <condition> else "<message>"` reaches the
# constraint diagnostics exactly as the equivalent `where (condition,
# "message")` does. The two forms differ only in surface syntax, so these are
# the `where_message_errors.mojo` and `where_message_conformance.mojo` cases
# respelled, and the expected notes are character-for-character the same.
#
# Each section uses its own struct/function decl so per-section diagnostic
# notes don't bleed across test sites.
# RUN: %parse-mojo-isolated -verify-diagnostics %s
##===----------------------------------------------------------------------===##
# Satisfied constraint with a message - positive case
##===----------------------------------------------------------------------===##
# The message must not affect constraint checking on the happy path.
struct SatisfiedStruct[N: Int]
where N > 0 else "N must be positive":
pass
def use_satisfied_struct():
var x: SatisfiedStruct[5]
##===----------------------------------------------------------------------===##
# Violated struct body constraint - message in the note
##===----------------------------------------------------------------------===##
# expected-note @below {{'ViolatedStruct' declared here}}
struct ViolatedStruct[N: Int]
# expected-note @below {{constraint declared here evaluated to False, expected '(N > Int(0))': N must be positive}}
where N > 0 else "N must be positive":
pass
def use_violated_struct():
# expected-error @below {{violated constraint}}
var x: ViolatedStruct[-1]
##===----------------------------------------------------------------------===##
# Violated function constraint - message in the note
##===----------------------------------------------------------------------===##
# expected-note @below {{function declared here}}
def gated_fn[sc: Int]()
# expected-note @below {{constraint declared here evaluated to False, expected '(sc > Int(1))': scaling factor must be greater than 1}}
where sc > 1 else "scaling factor must be greater than 1":
pass
def use_gated_fn():
# expected-error @below {{invalid call to 'gated_fn': violated constraint}}
gated_fn[0]()
##===----------------------------------------------------------------------===##
# A parenthesized message wrapping across lines reaches the note joined up
##===----------------------------------------------------------------------===##
# expected-note @below {{function declared here}}
def wrapped_msg_fn[w: Int]()
# expected-note @below {{constraint declared here evaluated to False, expected '(w > Int(0))': the width must be positive and no wider than a warp}}
where w > 0 else (
"the width must be positive "
"and no wider than a warp"
):
pass
def use_wrapped_msg_fn():
# expected-error @below {{invalid call to 'wrapped_msg_fn': violated constraint}}
wrapped_msg_fn[0]()
##===----------------------------------------------------------------------===##
# Violated conditional conformance - message on the conformance diagnostic
##===----------------------------------------------------------------------===##
trait Marker:
pass
struct No:
pass
struct GenBox[T: Deinitable](
# expected-note @below {{failed constraint: GenBox[T] requires T to be a Marker}}
Marker where conforms_to(T, Marker) else "GenBox[T] requires T to be a Marker"
):
pass
# expected-note @below {{function declared here}}
def wants_marker[U: Marker & Deinitable](x: U):
pass
def use_gen_box(b: GenBox[No]):
# expected-error @below {{does not conform to trait 'Deinitable & Marker'}}
wants_marker(b)
@@ -0,0 +1,147 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
# Test negative parse cases for the `where <condition> else "<message>"` form.
# As with `where (condition, "message")`, only string literals are accepted:
# a non-literal expression would need comptime evaluation that the parser
# cannot perform, so it is rejected with the same targeted diagnostic (see
# `where_message_parse_errors.mojo`).
# RUN: %parse-mojo-isolated -verify-diagnostics %s
trait Base:
pass
trait Extra:
pass
##===----------------------------------------------------------------------===##
# Non-literal message expression (identifier)
##===----------------------------------------------------------------------===##
# expected-error @below {{the message in a 'where' clause must be a string literal}}
def non_literal_message[x: Int]() where x > 0 else x:
pass
##===----------------------------------------------------------------------===##
# Non-literal message expression (alias reference)
##===----------------------------------------------------------------------===##
comptime MSG = "must be positive"
# expected-error @below {{the message in a 'where' clause must be a string literal}}
def alias_message[x: Int]() where x > 0 else MSG:
pass
##===----------------------------------------------------------------------===##
# A t-string is not a string literal
##===----------------------------------------------------------------------===##
# expected-error @below {{the message in a 'where' clause must be a string literal}}
def t_string_message[x: Int]() where x > 0 else t"x is {x}":
pass
##===----------------------------------------------------------------------===##
# Parentheses may wrap the message, but not turn it into an expression
##===----------------------------------------------------------------------===##
# expected-error @below {{the message in a 'where' clause must be a string literal}}
def paren_non_literal[x: Int]() where x > 0 else (x):
pass
##===----------------------------------------------------------------------===##
# Non-literal message on a struct trailing constraint
##===----------------------------------------------------------------------===##
# expected-error @below {{the message in a 'where' clause must be a string literal}}
struct StructNonLiteral[N: Int] where N > 0 else N < 10:
pass
##===----------------------------------------------------------------------===##
# Non-literal message on a conformance-list constraint
##===----------------------------------------------------------------------===##
# expected-error @below {{the message in a 'where' clause must be a string literal}}
struct CondConfNonLiteral[T: Base](Extra where conforms_to(T, Extra) else T):
pass
##===----------------------------------------------------------------------===##
# The message may be written once, in one form or the other -- not both
##===----------------------------------------------------------------------===##
# expected-error @below {{a 'where' clause takes at most one message: prefer 'where condition else "message"'}}
def both_forms[x: Int]() where (x > 0, "paren form") else "else form":
pass
struct CondConfBothForms[T: Base](
# expected-error @below {{a 'where' clause takes at most one message: prefer 'where condition else "message"'}}
Extra where (conforms_to(T, Extra), "paren form") else "else form"
):
pass
##===----------------------------------------------------------------------===##
# `else` with the message left out entirely
##===----------------------------------------------------------------------===##
# expected-error @below {{expected a string literal message after 'else'}}
def missing_message[x: Int]() where x > 0 else:
pass
# The conformance-list entry separator terminates the clause the same way.
struct CondConfMissingMessage[T: Base](
# expected-error @below {{expected a string literal message after 'else'}}
Extra where conforms_to(T, Extra) else, Base
):
pass
# expected-error @below {{expected a string literal message after 'else'}}
comptime AliasMissingMessage[T: AnyType] where conforms_to(T, Extra) else = T
##===----------------------------------------------------------------------===##
# A dedented `else` is the start of a new statement, not this clause's message
##===----------------------------------------------------------------------===##
# The dedented `else` lands at file scope, and a bare file-scope statement that
# fails to parse ends the module parse (unlike a bad decl body, which is
# contained by decl boundary scanning). So this case must stay last: anything
# below it would silently produce no diagnostics at all.
# expected-error @+1 {{expected ':' in function definition}}
def dedented_else[x: Int]() where x > 0
# expected-error @below {{unexpected token in expression}}
else "":
pass
@@ -0,0 +1,272 @@
# ===----------------------------------------------------------------------=== #
# 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.
# ===----------------------------------------------------------------------=== #
# Surfacing conditional-conformance `where` clauses as notes on
# conformance-failure diagnostics (generic trait bounds, ancestors, packs).
# Notes say "failed" or "unproven"; a user message is an optional suffix.
#
# Instance-to-trait bindings are category mismatches, not covered here.
# Each scenario uses its own struct so notes don't bleed across sites.
# RUN: %parse-mojo-isolated -verify-diagnostics %s
trait Marker:
pass
struct Yes(Marker):
pass
struct No:
pass
##===----------------------------------------------------------------------===##
# Satisfied conditional conformance - positive case (no error, no note).
##===----------------------------------------------------------------------===##
struct OkBox[T: Deinitable](
Marker where (conforms_to(T, Marker), "OkBox[T] is a Marker only when T is")
):
pass
def wants_marker_ok[U: Marker & Deinitable](x: U):
pass
def use_ok(b: OkBox[Yes]):
wants_marker_ok(b)
##===----------------------------------------------------------------------===##
# Violated via a generic trait-bounded parameter.
##===----------------------------------------------------------------------===##
struct GenBox[T: Deinitable](
# expected-note @below {{failed constraint: GenBox[T] requires T to be a Marker}}
Marker where (conforms_to(T, Marker), "GenBox[T] requires T to be a Marker")
):
pass
# expected-note @below {{function declared here}}
def wants_marker_gen[U: Marker & Deinitable](x: U):
pass
def use_gen(b: GenBox[No]):
# expected-error @below {{does not conform to trait 'Deinitable & Marker'}}
wants_marker_gen(b)
##===----------------------------------------------------------------------===##
# Same path without a user message: the note is still emitted at the `where`.
##===----------------------------------------------------------------------===##
struct PlainBox[T: Deinitable](
# expected-note @below {{failed constraint}}
Marker where conforms_to(T, Marker)
):
pass
# expected-note @below {{function declared here}}
def wants_marker_plain[U: Marker & Deinitable](x: U):
pass
def use_plain(b: PlainBox[No]):
# expected-error @below {{does not conform to trait 'Deinitable & Marker'}}
wants_marker_plain(b)
##===----------------------------------------------------------------------===##
# Requiring a propagated ancestor trait: the message is written on the derived
# conformance but is carried down to the propagated ancestor constraint, so
# requiring the bare ancestor still surfaces it (see the design doc).
##===----------------------------------------------------------------------===##
trait Base:
pass
trait Refined(Base):
pass
struct RefinedBox[T: Deinitable](
# expected-note @below {{failed constraint: RefinedBox[T] requires T to be a Marker}}
Refined where (conforms_to(T, Marker), "RefinedBox[T] requires T to be a Marker")
):
pass
# expected-note @below {{function declared here}}
def wants_base[U: Base & Deinitable](x: U):
pass
def use_ancestor(b: RefinedBox[No]):
# expected-error @below {{does not conform to trait 'Deinitable & Base'}}
wants_base(b)
##===----------------------------------------------------------------------===##
# A conformance satisfied by a caller `where` assumption is NOT reported: only
# the still-unproven conformance's message is surfaced. (The absence of a note
# for the CommonA message is enforced by -verify-diagnostics: an unexpected
# note fails the test.)
##===----------------------------------------------------------------------===##
trait MarkerA:
pass
trait MarkerB:
pass
trait CommonA:
pass
trait CommonB:
pass
struct TwoBox[T: Deinitable](
CommonA where (conforms_to(T, MarkerA), "TwoBox needs MarkerA for CommonA"),
# expected-note @below {{unproven constraint: TwoBox needs MarkerB for CommonB}}
CommonB where (conforms_to(T, MarkerB), "TwoBox needs MarkerB for CommonB"),
):
pass
# expected-note @below {{function declared here}}
def wants_both[U: CommonA & CommonB & Deinitable](x: U):
pass
# V is assumed to be MarkerA (so the CommonA conformance holds) but nothing is
# assumed about MarkerB, so only CommonB remains unproven.
def use_two[V: Deinitable](b: TwoBox[V]) where (
conforms_to(V, MarkerA), "V is a MarkerA"
):
# expected-error @below {{does not conform to trait}}
wants_both(b)
##===----------------------------------------------------------------------===##
# When neither marker is available, BOTH conditional conformances are unproven
# and both messages surface as separate notes at the one call site.
##===----------------------------------------------------------------------===##
struct BothBox[T: Deinitable](
# expected-note @below {{unproven constraint: BothBox needs MarkerA for CommonA}}
CommonA where (conforms_to(T, MarkerA), "BothBox needs MarkerA for CommonA"),
# expected-note @below {{unproven constraint: BothBox needs MarkerB for CommonB}}
CommonB where (conforms_to(T, MarkerB), "BothBox needs MarkerB for CommonB"),
):
pass
# expected-note @below {{function declared here}}
def wants_both_nm[U: CommonA & CommonB & Deinitable](x: U):
pass
def use_both_none[V: Deinitable](b: BothBox[V]):
# expected-error @below {{does not conform to trait}}
wants_both_nm(b)
##===----------------------------------------------------------------------===##
# Violated via a variadic trait-bounded pack element.
##===----------------------------------------------------------------------===##
struct PackBox[T: Deinitable](
# expected-note @below {{failed constraint: PackBox[T] requires T to be a Marker}}
Marker where (conforms_to(T, Marker), "PackBox[T] requires T to be a Marker")
):
pass
# expected-note @below {{function declared here}}
def wants_markers[*Ts: Marker & Deinitable](*args: *Ts):
pass
def use_pack(b: PackBox[No]):
# expected-error @below {{does not conform to trait}}
wants_markers(b)
##===----------------------------------------------------------------------===##
# Refuted and unproven in the same query: `U` is concretely not a MarkerA, and
# nothing is known about `T`. The verdict is `no`, so only the refutation is
# reported -- proving MarkerB would not make the conformance hold. The absent
# note is the point of this case, and -verify-diagnostics enforces it.
##===----------------------------------------------------------------------===##
struct MixedBox[T: Deinitable, U: Deinitable](
# expected-note @below {{failed constraint: MixedBox needs MarkerA for CommonA}}
CommonA where (conforms_to(U, MarkerA), "MixedBox needs MarkerA for CommonA"),
CommonB where (conforms_to(T, MarkerB), "MixedBox needs MarkerB for CommonB"),
):
pass
# expected-note @below {{function declared here}}
def wants_both_mixed[W: CommonA & CommonB & Deinitable](x: W):
pass
def use_mixed[V: Deinitable](b: MixedBox[V, No]):
# expected-error @below {{does not conform to trait}}
wants_both_mixed(b)
##===----------------------------------------------------------------------===##
# Same, with the refutation arriving after the unproven one rather than before.
# The verdict is still `no` and still reports only the refutation, so the
# unproven constraint gathered first has to be dropped once it shows up.
##===----------------------------------------------------------------------===##
struct LateMixedBox[T: Deinitable, U: Deinitable](
CommonA where (conforms_to(T, MarkerA), "LateMixedBox needs MarkerA for CommonA"),
# expected-note @below {{failed constraint: LateMixedBox needs MarkerB for CommonB}}
CommonB where (conforms_to(U, MarkerB), "LateMixedBox needs MarkerB for CommonB"),
):
pass
# expected-note @below {{function declared here}}
def wants_both_late[W: CommonA & CommonB & Deinitable](x: W):
pass
def use_late_mixed[V: Deinitable](b: LateMixedBox[V, No]):
# expected-error @below {{does not conform to trait}}
wants_both_late(b)
@@ -0,0 +1,130 @@
# ===----------------------------------------------------------------------=== #
# 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 the optional message on a `where` clause
# (`where (condition, "message")`) is surfaced in constraint diagnostics: in
# the "evaluated to False" note when a constraint is violated, and in the
# "needs evidence for" note when a constraint is inconclusive.
#
# Each section uses its own struct/function decl so per-section diagnostic
# notes don't bleed across test sites (mirrors the convention in
# `struct_body_constraints.mojo`).
# RUN: %parse-mojo-isolated -verify-diagnostics %s
##===----------------------------------------------------------------------===##
# Satisfied constraint with a message - positive case
##===----------------------------------------------------------------------===##
# The message must not affect constraint checking on the happy path.
struct SatisfiedStruct[N: Int]
where (N > 0, "N must be positive"):
pass
def use_satisfied_struct():
var x: SatisfiedStruct[5]
##===----------------------------------------------------------------------===##
# Violated struct body constraint - message in the note
##===----------------------------------------------------------------------===##
# expected-note @below {{'ViolatedStruct' declared here}}
struct ViolatedStruct[N: Int]
# expected-note @below {{constraint declared here evaluated to False, expected '(N > Int(0))': N must be positive}}
where (N > 0, "N must be positive"):
pass
def use_violated_struct():
# expected-error @below {{violated constraint}}
var x: ViolatedStruct[-1]
##===----------------------------------------------------------------------===##
# Violated function constraint - message in the note
##===----------------------------------------------------------------------===##
# expected-note @below {{function declared here}}
def gated_fn[sc: Int]()
# expected-note @below {{constraint declared here evaluated to False, expected '(sc > Int(1))': scaling factor must be greater than 1}}
where (sc > 1, "scaling factor must be greater than 1"):
pass
def use_gated_fn():
# expected-error @below {{invalid call to 'gated_fn': violated constraint}}
gated_fn[0]()
##===----------------------------------------------------------------------===##
# Violated compound (and) constraint - one clause keeps one message
##===----------------------------------------------------------------------===##
# `where (A and B, "msg")` is a single constraint carrying the message.
# expected-note @below {{'CompoundStruct' declared here}}
struct CompoundStruct[N: Int]
# expected-note @below {{constraint declared here evaluated to False, expected '(N < Int(10)) if (N > Int(0)) else (N > Int(0))': N must be in (0, 10)}}
where (N > 0 and N < 10, "N must be in (0, 10)"):
pass
def use_compound_struct():
# expected-error @below {{violated constraint}}
var x: CompoundStruct[-1]
##===----------------------------------------------------------------------===##
# Inconclusive constraint - message in the "needs evidence" note
##===----------------------------------------------------------------------===##
# Helper that represents an unprovable constraint since it is not
# always_inline("builtin").
# expected-note @below {{cannot evaluate call to non-builtin function declared here}}
def is_prime(x: Int) -> Bool:
return x > 1
# expected-note @below {{cannot prove constraint}}
def inconclusive_fn[x: Int]()
# expected-note @below {{constraint declared here needs evidence for 'is_prime(Int(2))': x must be prime}}
where (is_prime(x), "x must be prime"):
pass
def use_inconclusive_fn():
# expected-error @below {{invalid call to 'inconclusive_fn': lacking evidence to prove correctness}}
# expected-note @below {{provide evidence for the constraint here to aid in candidate selection}}
inconclusive_fn[2]()
##===----------------------------------------------------------------------===##
# Violated alias (comptime) constraint - message in the note
##===----------------------------------------------------------------------===##
comptime GatedAlias[N: Int]
# expected-note @below {{constraint declared here evaluated to False, expected '(N > Int(0))': alias requires a positive N}}
where (N > 0, "alias requires a positive N") = N
def use_gated_alias():
# expected-error @below {{violated constraint}}
comptime x = GatedAlias[-1]
@@ -0,0 +1,81 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
# Test negative parse cases for the optional message on `where` clauses. A
# message is written `where (condition, "message")`. For now only string
# literals are accepted as the message: a non-literal expression would need
# comptime evaluation that the parser cannot perform, so it is rejected with a
# targeted diagnostic.
# RUN: %parse-mojo-isolated -verify-diagnostics %s
##===----------------------------------------------------------------------===##
# Non-literal message expression (identifier)
##===----------------------------------------------------------------------===##
# expected-error @below {{the message in a 'where' clause must be a string literal}}
def non_literal_message[x: Int]() where (x > 0, x):
pass
##===----------------------------------------------------------------------===##
# Non-literal message expression (alias reference)
##===----------------------------------------------------------------------===##
comptime MSG = "must be positive"
# expected-error @below {{the message in a 'where' clause must be a string literal}}
def alias_message[x: Int]() where (x > 0, MSG):
pass
##===----------------------------------------------------------------------===##
# Non-literal message on a struct trailing constraint
##===----------------------------------------------------------------------===##
# expected-error @below {{the message in a 'where' clause must be a string literal}}
struct StructNonLiteral[N: Int] where (N > 0, N < 10):
pass
##===----------------------------------------------------------------------===##
# Non-literal message on a conformance-list constraint
##===----------------------------------------------------------------------===##
trait Base:
pass
trait Extra:
pass
# expected-error @below {{the message in a 'where' clause must be a string literal}}
struct CondConfNonLiteral[T: Base](Extra where (conforms_to(T, Extra), T)):
pass
##===----------------------------------------------------------------------===##
# Wrong tuple arity: a `where` clause takes a condition and an optional message
##===----------------------------------------------------------------------===##
# expected-error @below {{a 'where' clause takes a condition and an optional message: 'where (condition, "message")'}}
def too_many_elements[x: Int]() where (x > 0, "msg", "extra"):
pass
@@ -0,0 +1,57 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
#
# Diagnostics for undischarged identity and conformance constraints name the
# proposition the constraint folded into, so the caller is told what evidence
# is missing.
#
# RUN: %parse-mojo-isolated -verify-diagnostics %s
# expected-note @below {{cannot prove constraint for candidate}}
def needs_same[A: AnyType, B: AnyType]()
# expected-note @below {{constraint declared here needs evidence for 'Bool(identical(A, B))'}}
where A == B:
pass
def missing_identity[A: AnyType, B: AnyType]():
# expected-error @below {{invalid call to 'needs_same': lacking evidence to prove correctness}}
# expected-note @below {{provide evidence for the constraint here to aid in candidate selection}}
needs_same[A, B]()
# expected-note @below {{cannot prove constraint for candidate}}
def needs_intable[T: AnyType]()
# expected-note @below {{constraint declared here needs evidence for 'conforms_to(T, Intable)'}}
where conforms_to(T, Intable):
pass
def missing_conformance[T: AnyType]():
# expected-error @below {{invalid call to 'needs_intable': lacking evidence to prove correctness}}
# expected-note @below {{provide evidence for the constraint here to aid in candidate selection}}
needs_intable[T]()
# expected-note @below {{cannot prove constraint for candidate}}
def needs_chain[A: AnyType, B: AnyType, C: AnyType]()
# expected-note @below {{constraint declared here needs evidence for 'Bool(identical(B, C)) if Bool(identical(A, C)) else Bool(identical(A, C))'}}
where A == C and B == C:
pass
def missing_chain[A: AnyType, B: AnyType, C: AnyType]():
# expected-error @below {{invalid call to 'needs_chain': lacking evidence to prove correctness}}
# expected-note @below {{provide evidence for the constraint here to aid in candidate selection}}
needs_chain[A, B, C]()