feat: move corpus to library

This commit is contained in:
alexm committed 2026-10-06 09:57:04 -04:00
1 parent df12b2a008
commit 9d351b4a0f
1301 files changed
+941859 -4

No files matched your search

+31
View File
@@ -0,0 +1,31 @@
# Mojo corpus sources (Mojo 1.1.0, `mojo_1_1_0`)
Generated by `python3 scripts/mojo/corpus.py harvest`. Do not edit: change `mojo/pin.json` and re-harvest.
Every item in the corpus records the same provenance per file in its manifest.
| source | repository | from | zip sha256 | licence |
|---|---|---|---|---|
| modular | modular/modular | commit `c6fa49f712fe` (mojo/v1.1.0) | `5220972c0e4d2a44` | Apache-2.0 WITH LLVM-exception (per file headers; confirm the docs carry the same licence) |
| mojo-quest | modular/mojo-quest (unconfirmed) | commit `3576e6105381` (3576e6105381bb6f956f405408ea8202ddf1eb6e) | `8b64817dbe07aa13` | Apache-2.0 WITH LLVM-exception per file headers; the repo has no LICENSE file, so confirm with Modular before showing exercises to students |
| mojo-syntax | modular/mojo-syntax | commit `48cdeac4f6b5` (48cdeac4f6b542e0b50666a5725fdfadf6188836) | `2c6ec7c70921e361` | MIT |
| skills | modular/skills | commit `0288f88deff5` (0288f88deff5e4d936ed1b84db125f2b9bafc0d1) | `7511fa319866022e` | Apache-2.0 WITH LLVM-exception |
| vscode-mojo | modular/vscode-mojo | commit `e60719a9fed8` (e60719a9fed899466072fef4b499041f9c4247ad) | `3202b75dab3756a0` | Apache-2.0 |
## What each processor found
- **quest**: tickets 85, items 170, byExpectation {'pass': 85, 'fail': 85}, runChecks 78
- **manual**: codeSamples 169, snippets 31, skippedNewer 0
- **diagnostics**: files 174, annotations 2620, byPass {'other': 38, 'lifetimes': 9, 'parser': 127}, byKind {'error': 1644, 'note': 827, 'warning': 149}, maybeReproducible 132
- **tokens**: keywords 61, publicKeywords 47, punctuation 49, softKeywords 6, removedSoft ['fn', 'read'], decorators 11, prelude 160
- **messages**: messages 716, withFixits 23, byPass {'parser': 682, 'lifetimes': 34}
- **release**: snapshot same, newestRelease 1.1.0, sections 32, nightlyEntries 0
- **syntax**: cases 30, files 2, flaggedOlder 2
- **editor**: extensionVersion 26.6.1, extensions ['.mojo', '.🔥'], hasIndentationRules True
- **skill**: entries 30
- **stdindex**: names 633, ambiguous 38, packages 42, raisingPrelude 5
## Notes from the pin
- **modular**: The compiler, stdlib, manual, release notes, and compiler tests. Mojo releases are tagged mojo/vX.Y.Z in this repository (the platform's own tags are modular/vX.Y). Only the stdlib and the release notes are required to be present; a processor whose inputs are missing at a ref (the compiler sources, say) is skipped with a warning and keeps its previous output.
- **mojo-quest**: Mojo Quest pins mojo_1_1_0 itself (src/lib/compile.ts), so its main branch at a commit where that is still true is the right ref. The repository name is inferred: the zip carries no remote URL.
- **skills**: The skill targets the latest Mojo, which can be ahead of the pin; its table is a list of candidates, not a ruling.
@@ -0,0 +1,51 @@
# ===----------------------------------------------------------------------=== #
# 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: kgen %s -elaborate -verify-diagnostics
# expected-error @+2{{function instantiation failed}}
@export
def wrong_attribute_name(a: Int, b: Int) abi("Mojo") raises -> Bool:
comptime pred_attr = __mlir_attr.`#index.cmp_predicate<sle>`
# expected-note @below {{unexpected attribute 'foobar' on operation}}
var res = __mlir_op.`index.cmp`[foobar=pred_attr](a, b)
return res
# expected-error @+2{{function instantiation failed}}
@export
def extra_attribute(a: Int, b: Int) abi("Mojo") raises -> Bool:
comptime pred_attr = __mlir_attr.`#index.cmp_predicate<sle>`
# expected-note @below {{unexpected attribute 'foobar' on operation}}
var res = __mlir_op.`index.cmp`[pred=pred_attr, foobar=pred_attr](
a.__mlir_index__(), b.__mlir_index__()
)
return res
# expected-error @+2{{function instantiation failed}}
@export
def invalid_predicate_passed(x: Int, y: Int) abi("Mojo") -> Bool:
def pred() -> __mlir_type.`!kgen.string`:
return __mlir_attr[`"xyz" : !kgen.string`]
def get_pred() -> __mlir_type.`!kgen.deferred`:
return __mlir_deferred_attr[`#index.cmp_predicate<`, pred(), `>`]
# expected-note @below {{invalid MLIR attribute: failed to parse IndexCmpPredicateAttr parameter 'value' which is to be a `::mlir::index::IndexCmpPredicate`}}
var z = __mlir_op.`index.cmp`[pred=get_pred()](x, y)
return z
@@ -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: kgen %s -elaborate -verify-diagnostics
# Counterpart to callback_inferred_addrspace.mojo: there the deferred type stays
# abstract (an escaping parameter reference) so the materialization error is
# suppressed. Here the parameter `n` is fully bound at materialization, leaving
# no escaping reference, but the resulting concrete type string is unparseable.
# The "invalid MLIR type in deferred_type" error must fire.
@no_inline
def use[
n: Int
]() -> __mlir_deferred_type[`!llvm.array<`, +n.__mlir_index__(), ` bogus f32>`]:
return __mlir_op.`llvm.mlir.undef`[
_type=__mlir_deferred_type[
`!llvm.array<`, +n.__mlir_index__(), ` bogus f32>`
]
]()
# expected-error @+1 {{function instantiation failed}}
def main():
comptime sz: Int = 4
# expected-note @+1 {{invalid MLIR type in deferred_type: !llvm.array<4 bogus f32>}}
_ = use[sz]()
print("ok")
@@ -0,0 +1,143 @@
# ===----------------------------------------------------------------------=== #
# 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: kgen %s -elaborate=no-use-parametric-interpreter -verify-diagnostics
# RUN: not kgen -elaborate -D TEST_RECURSION2=1 %s 2>&1 | FileCheck %s --check-prefix=CHECK-RECURSION2
# RUN: not kgen -elaborate -D TEST_RECURSION3=1 %s 2>&1 | FileCheck %s --check-prefix=CHECK-RECURSION3
from std.collections.string.string_span import StaticString, _get_kgen_string
from std.sys import get_defined_bool
# expected-error @+2{{function instantiation failed}}
@export
def entry_method() abi("Mojo"):
foo() # expected-note {{call expansion failed}}
@always_inline("nodebug")
def foo():
bar() # expected-note {{call expansion failed}}
@always_inline("nodebug")
def bar():
baz() # expected-note {{call expansion failed}}
@always_inline("nodebug")
def baz():
__mlir_op.`kgen.param.assert`[
cond=__mlir_attr.`#kgen.simd<false> : !kgen.scalar<bool>`,
message="oops".value,
]() # expected-note {{constraint failed}}
# expected-error @+2{{function instantiation failed}}
@export
def test_no_params() abi("Mojo"):
no_parameters() # expected-note {{call expansion failed}}
# expected-note @+2{{function instantiation failed}}
@no_inline
def no_parameters():
parametric[1]() # expected-note {{call expansion failed}}
@no_inline
def parametric[param: Int](): # expected-note {{function instantiation failed}}
comptime assert ( # expected-note {{constraint failed: param must be 2}}
param == 2
), "param must be 2"
# This is copied so the note ends up in this file.
@always_inline("nodebug")
def constrained[cond: Bool, msg: StaticString]():
comptime msg_literal = _get_kgen_string[msg]()
__mlir_op.`kgen.param.assert`[
cond=cond.__mlir_bool__(), message=msg_literal
]()
# expected-error @+2{{function instantiation failed}}
@export
def test_comptime_assert() abi("Mojo"):
parametric_assert[1]() # expected-note {{call expansion failed}}
# expected-note @+2{{function instantiation failed}}
@no_inline
def parametric_assert[param: Int]():
# expected-note @below {{constraint failed: param must be 2}}
comptime assert param == 2, "param must be 2"
# This creates recursive cycles: foo[D] -> bar[D] -> foo[D] and foo[D] -> baz[D] -> foo[D]
def bar[D: Int]() -> Int:
comptime x = foo[D]()
return x
def baz[D: Int]() -> Int:
comptime x = foo[D]()
return x
def foo[D: Int]() -> Int:
var x = bar[D]()
# CHECK-RECURSION2: call expansion failed with parameter value(s): ("D": 2)
var y = baz[D]()
_ = x
_ = y
return y
def test_recursion2():
comptime run_test = get_defined_bool["TEST_RECURSION2", False]()
comptime if run_test:
# CHECK-RECURSION2: call expansion failed with parameter value(s): ("D": 2)
_ = foo[2]()
# CHECK-RECURSION2: function instantiation in parameter domain that recursively requires itself
# CHECK-RECURSION2: recursively instantiated through here
# This creates a recursive cycle: foo1[D] -> bar1[D] -> foo1[D]
def bar1[D: Int]() -> Int:
comptime x = foo1[D]()
return x
def foo1[D: Int]() -> Int:
# CHECK-RECURSION3: call expansion failed with parameter value(s): ("D": 1)
var x = bar1[D]()
return x
def test_recursion3():
comptime run_test = get_defined_bool["TEST_RECURSION3", False]()
comptime if run_test:
# CHECK-RECURSION3: call expansion failed with parameter value(s): ("D": 1)
_ = foo1[1]()
# CHECK-RECURSION3: function instantiation in parameter domain that recursively requires itself
# CHECK-RECURSION3: recursively instantiated through here
def main():
test_recursion2()
test_recursion3()
@@ -0,0 +1,71 @@
# ===----------------------------------------------------------------------=== #
# 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: kgen %s -elaborate -elaboration-error-limit=2 --num-threads=1 -verify-diagnostics
# RUN: not kgen %s -elaborate=use-parametric-interpreter -elaboration-error-limit=2 --num-threads=1 2>&1 | FileCheck %s --check-prefix=CHECK-PARAM
# COM: -elaborate=use-parametric-interpreter slight difference from -elaborate for error messages.
# Using FileCheck instead to check those with CHECK-PRAMA prefix.
# (TODO) error message for parametric interpreter is non-deterministic with limit=2, i.e.
# either combination of 2 out of foo, bar and baz can show up, hence not checking with a label
# expected-error @+2{{function instantiation failed}}
@export
def entry_method0() abi("Mojo"):
foo() # expected-note {{call expansion failed}}
# expected-error @+3{{function instantiation failed}}
# expected-note @+2{{too many errors emitted, stopping now}}
@export
def entry_method1() abi("Mojo"):
bar() # expected-note {{call expansion failed}}
@export
def entry_method2() abi("Mojo"):
baz()
# expected-note @+2{{function instantiation failed}}
@no_inline
def foo():
__mlir_op.`kgen.param.assert`[
cond=__mlir_attr.`#kgen.simd<false> : !kgen.scalar<bool>`,
message="oops".value,
]() # expected-note {{constraint failed}}
# CHECK-PARAM: function instantiation failed
# CHECK-PARAM: constraint failed
# expected-note @+2 {{function instantiation failed}}
@no_inline
def bar():
__mlir_op.`kgen.param.assert`[
cond=__mlir_attr.`#kgen.simd<false> : !kgen.scalar<bool>`,
message="oops".value,
]() # expected-note {{constraint failed}}
# CHECK-PARAM: function instantiation failed
# CHECK-PARAM: constraint failed
@no_inline
def baz():
__mlir_op.`kgen.param.assert`[
cond=__mlir_attr.`#kgen.simd<false> : !kgen.scalar<bool>`,
message="oops".value,
]()
# CHECK-PARAM: too many errors emitted, stopping now
@@ -0,0 +1,53 @@
# ===----------------------------------------------------------------------=== #
# 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: kgen -elaborate %s --verify-diagnostics
# RUN: not kgen -elaborate %s --elaboration-error-include-prelude 2>&1 | FileCheck %s --check-prefix=CHECK-PRELUDE
# RUN: not mojo --elaboration-error-include-prelude %s 2>&1 | FileCheck %s --check-prefix=CHECK-PRELUDE
# RUN: not kgen -elaborate %s --elaboration-error-include-prelude --elaboration-error-verbose=all-params 2>&1 | FileCheck %s --check-prefix=CHECK-VERBOSE
# RUN: not mojo --elaboration-error-include-prelude --elaboration-error-verbose=all-params %s 2>&1 | FileCheck %s --check-prefix=CHECK-VERBOSE
from std.collections.string.string_span import _get_kgen_string
# CHECK-PRELUDE: {{.*}}std/builtin/_startup.mojo
# CHECK-PRELUDE-SAME: error: function instantiation failed
# CHECK-VERBOSE: {{.*}}std/builtin/_startup.mojo
# CHECK-VERBOSE-SAME: error: function instantiation failed
# CHECK-PRELUDE: {{.*}}std/builtin/_startup.mojo
# CHECK-PRELUDE-SAME: note: call expansion failed with parameter value(s): (...)
# CHECK-VERBOSE: {{.*}}std/builtin/_startup.mojo
# CHECK-VERBOSE-SAME: note: call expansion failed with parameter value(s): ("main_func":
# CHECK-PRELUDE: {{.*}}std/builtin/_startup.mojo
# CHECK-PRELUDE-SAME: note: function instantiation failed
# CHECK-PRELUDE: {{.*}}std/builtin/_startup.mojo
# CHECK-PRELUDE-SAME: note: call expansion failed
@always_inline("nodebug")
def my_constrained[cond: Bool, msg: StaticString, *extra: StaticString]():
__mlir_op.`kgen.param.assert`[
cond=cond.__mlir_bool__(),
message=_get_kgen_string[msg, *extra](),
]() # expected-note {{constraint failed}}
# expected-note @below {{function instantiation failed}}
def my_func():
# expected-note @below {{call expansion failed}}
my_constrained[False, "foo"]()
# expected-error @below {{function instantiation failed}}
def main():
# expected-note @below {{call expansion failed}}
my_func()
@@ -0,0 +1,47 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
# RUN: kgen -elaborate %s --verify-diagnostics
# RUN: not kgen -elaborate %s --elaboration-error-include-prelude 2>&1 | FileCheck %s --check-prefix=CHECK-PRELUDE
# RUN: not mojo --elaboration-error-include-prelude %s 2>&1 | FileCheck %s --check-prefix=CHECK-PRELUDE
from std.collections.string.string_span import _get_kgen_string
# CHECK-PRELUDE: {{.*}}std/builtin/_startup.mojo
# CHECK-PRELUDE-SAME: error: function instantiation failed
# CHECK-PRELUDE: {{.*}}std/builtin/_startup.mojo
# CHECK-PRELUDE-SAME: note: call expansion failed
# CHECK-PRELUDE: {{.*}}std/builtin/_startup.mojo
# CHECK-PRELUDE-SAME: note: function instantiation failed
# CHECK-PRELUDE: {{.*}}std/builtin/_startup.mojo
# CHECK-PRELUDE-SAME: note: call expansion failed
@always_inline("nodebug")
def my_constrained[cond: Bool, msg: StaticString, *extra: StaticString]():
__mlir_op.`kgen.param.assert`[
cond=cond.__mlir_bool__(),
message=_get_kgen_string[msg, *extra](),
]() # expected-note {{constraint failed}}
# expected-note @below {{function instantiation failed}}
def my_func():
# expected-note @below {{call expansion failed}}
my_constrained[False, "foo"]()
# expected-error @below {{function instantiation failed}}
def main():
# expected-note @below {{call expansion failed}}
my_func()
@@ -0,0 +1,40 @@
# ===----------------------------------------------------------------------=== #
# 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: kgen -elaborate -elaboration-max-depth=128 --elaboration-error-verbose=no-params %s --verify-diagnostics
# RUN: not mojo build -elaboration-max-depth=128 --elaboration-error-verbose=no-params %s 2>&1 | FileCheck %s
from std.collections.string.string_span import _get_kgen_string
from std.sys import get_defined_bool
# expected-note @below {{function instantiation failed}}
# expected-note @below {{remaining errors after}}
# expected-note-re @below {{error recurses {{[0-9]+}} times}}
# expected-note-re @below {{elaborator expansion is {{[0-9]+}} levels deep - infinite recursion?}}
def self_recursion[i: Int]() -> Int:
# expected-note @below {{call expansion failed}}
# expected-warning @below {{self recursive call will cause an infinite loop}}
var x = self_recursion[i + 1]()
return x
# expected-error @below {{function instantiation failed}}
def main():
# expected-note @below {{call expansion failed}}
_ = self_recursion[1]()
# CHECK: self recursive call will cause an infinite loop
# CHECK: error recurses {{[0-9]+}} times
# CHECK: elaborator expansion is {{[0-9]+}} levels deep - infinite recursion?
@@ -0,0 +1,38 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
# RUN: kgen -elaborate %s --verify-diagnostics
# This creates a recursive cycle: foo[D] -> bar[D] -> foo[D]
# expected-note @below {{function instantiation failed}}
# expected-note @below {{function instantiation in parameter domain that recursively requires itself}}
# expected-note @below {{back to parameter domain function call here}}
def bar[D: Int]() -> Int:
comptime x = foo[D]()
return x
# expected-note @below {{function instantiation failed}}
def foo[D: Int]() -> Int:
# expected-note @below {{recursively instantiated through here}}
# expected-note @below {{call expansion failed with parameter value(s): ("D": 1)}}
var x = bar[D]()
return x
# expected-error @below {{function instantiation failed}}
def main():
# expected-note @below {{call expansion failed with parameter value(s): ("D": 1)}}
_ = foo[1]()
@@ -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.
# ===----------------------------------------------------------------------=== #
# RUN: kgen -elaborate %s --verify-diagnostics
# This creates recursive cycles: foo[D] -> bar[D] -> foo[D] and foo[D] -> baz[D] -> foo[D]
# expected-note @below {{recursively instantiated through here}}
def bar[D: Int]() -> Int:
comptime x = foo[D]()
return x
# expected-note @below {{function instantiation failed}}
# expected-note @below {{function instantiation in parameter domain that recursively requires itself}}
def baz[D: Int]() -> Int:
comptime x = foo[D]()
return x
# expected-note @below {{function instantiation failed}}
def foo[D: Int]() -> Int:
# expected-note @below {{recursively instantiated through here}}
var x = bar[D]()
# expected-note @below {{call expansion failed with parameter value(s): ("D": 2)}}
var y = baz[D]()
_ = x
_ = y
return y
# expected-error @below {{function instantiation failed}}
def main():
# expected-note @below {{call expansion failed with parameter value(s): ("D": 2)}}
_ = foo[2]()
@@ -0,0 +1,36 @@
# ===----------------------------------------------------------------------=== #
# 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: kgen -elaborate %s --verify-diagnostics
# Every generator in this cycle is trivial enough for `ApplyInliner` to give it
# an inlined form: the body is just a parameter constant and a return. That form
# then applies the generator it came from, so expanding it re-derives the same
# apply forever and used to overflow the stack before the elaborator ever saw
# the cycle. The sibling recursion tests route their cycle through a generator
# holding a runtime call, which never gets an inlined form, so the expansion has
# nothing to loop on there. See MOCO-4518.
# expected-note @below {{function instantiation failed}}
# expected-note @below {{function instantiation in parameter domain that recursively requires itself}}
# expected-note @below {{function recursively calls itself in the parameter domain}}
def g[n: Int]() -> Int:
comptime m = g[n]()
return m
# expected-error @below {{function instantiation failed}}
def main():
# expected-note @below {{call expansion failed with parameter value(s): ("n": 1)}}
print(g[1]())
@@ -0,0 +1,56 @@
# ===----------------------------------------------------------------------=== #
# 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: kgen -elaborate %s --verify-diagnostics
# Verifies that a type error inside a mutually
# recursive function (an elaboration SCC) is surfaced through the SCC boundary
# to the caller.
# expected-note @below {{function instantiation failed}}
def check_allowed[T: AnyType]():
comptime assert ( # expected-note {{constraint failed: type not allowed}}
False
), "type not allowed"
trait Visitor:
def visit(self, x: Int) raises -> Int:
return 0
# expected-note @below {{function instantiation failed}}
def dispatch[V: Visitor](v: V, x: Int) raises -> Int:
# expected-note @below {{call expansion failed}}
return v.visit(x)
struct BadVisitor(Visitor):
def __init__(out self):
pass
# expected-note @below {{function instantiation failed}}
def visit(self, x: Int) raises -> Int:
# dispatch(self, x) is the intra-SCC back-edge and is not in the chain.
_ = dispatch(self, x)
# expected-note @below {{call expansion failed}}
check_allowed[String]()
return 0
# expected-error @below {{function instantiation failed}}
def main() raises:
var v = BadVisitor()
# expected-note @below {{call expansion failed with parameter value(s): (...)}}
_ = dispatch(v, 1)
@@ -0,0 +1,95 @@
# ===----------------------------------------------------------------------=== #
# 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.
# ===----------------------------------------------------------------------=== #
def fn_missing_constraint[n: Int]() where n > 0:
pass
def overloaded_function(n: Int):
pass
def overloaded_function(n: Float64):
pass
def overloaded_function(n: Int, m: Float64):
pass
@fieldwise_init
struct PosOnlyStruct[a: Int, b: Int, /, c: Int = 9]:
pass
struct DeprecatedImplicitConversion:
@implicit(deprecated=True)
def __init__(out self, value: Int):
pass
@always_inline("builtin")
def foldable_predicate(y: Int) -> Bool:
return y > 10
def constraint_fn[a: Int, b: Int]() where a > 0:
pass
def unfoldable_predicate(y: Int) -> Bool:
return y > 2
def unprovable_constraints[x: Int]() where unfoldable_predicate(x):
pass
struct Conflict:
pass
trait ConflictTraitName:
def test[a: Int](self):
pass
trait NoDefaultFunc:
def doSomething(self):
...
trait StillNoDefaultFunc(NoDefaultFunc):
def doEverything(self):
...
trait UnprovableCandidateTrait:
# expected-note @below {{required by trait method here}}
def handle(self):
...
trait ConflictTraitMethod:
def test(self) -> Bool:
return True
trait OtherConflictTraitMethod(ConflictTraitMethod):
def test(self) -> Bool:
return False
trait TraitWithMember:
comptime N: Int
@@ -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.
# ===----------------------------------------------------------------------=== #
# RUN: kgen %s -elaborate -verify-diagnostics
@export
def origins_dont_exist_at_elaboration_time(
a: String, b: String
) abi("Mojo") -> Bool:
# expected-error @+1 {{origin equality may only be tested in 'where' clauses}}
return origin_of(b).contains[origin_of(a)]
@@ -0,0 +1,36 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
# RUN: %parse-mojo-isolated %s -mlir-print-debuginfo | kgen-opt -lower-semantic-cf -check-lifetimes -verify-parameters -verify-diagnostics
def takeIt[T: def () -> None, //](state: T):
state()
struct MoveMe(Movable):
var x:Int
def __init__(out self, *, deinit move: Self):
self.x = move.x
def __deinit__(deinit self:Self):
pass
def use(d:MoveMe):
pass
# CHECK-LABEL: lit.fn @"toy
def toy(var byMove: MoveMe): # expected-note {{'byMove' declared here}}
def myclosure() {var byMove^}:
use(byMove)
use(byMove) # expected-error {{use of uninitialized value 'byMove'}}
takeIt(myclosure)
@@ -0,0 +1,60 @@
# ===----------------------------------------------------------------------=== #
# 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
# A closure cannot derive an interior origin from a captured container while
# an interior reference to the same container is also captured.
# TODO: lift this limitation
struct MyList[T: AnyType](Movable where False):
var data: UnsafePointer[Self.T, UntrackedOrigin[mut=True]]
def __init__(out self):
self.data = UnsafePointer[
Self.T, UntrackedOrigin[mut=True]].unsafe_dangling()
def __deinit__(deinit self):
pass
@__unsafe_nested_origins_read_only
def __getitem__(
ref self,
) -> ref[self.data._get_ref_with_unsafe_interior_origin["element"](self)] Self.T:
return self.data._get_ref_with_unsafe_interior_origin["element"](self)
struct MyPtr[origin: Origin[mut=False]]:
var p: UnsafePointer[Int, Self.origin]
def __init__(out self, *, ref [Self.origin] to: Int):
self.p = UnsafePointer[Int, Self.origin].address_of(to)
def get(self) -> Int:
return self.p[]
def test_derive_and_capture_interior[O: Origin[mut=True]](ref [O] list: MyList[Int]):
var p = MyPtr(to=list[])
@always_inline
def inner() {imm}:
# expected-error @below {{cannot derive an interior origin from a captured container while an interior reference to the container is also captured}}
_ = list[]
_ = p.get()
inner()
def main():
var list = MyList[Int]()
test_derive_and_capture_interior(list)
@@ -0,0 +1,71 @@
# ===----------------------------------------------------------------------=== #
# 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
# COM: Negative companion to closure_wrapper_marker_conformances.mojo
# COM: (MOCO-4240). Marker-trait conformance on closure wrappers must stay
# COM: gated on the closure's actual properties: a memory-convention closure
# COM: is not RegisterPassable, and a closure move-capturing a non-copyable
# COM: value is not ImplicitlyCopyable.
# A plain (non-register-passable) struct: capturing it forces the closure to
# the memory convention.
struct MemOnly(Copyable, ImplicitlyCopyable, Movable, Deinitable):
var x: Int
def __init__(out self):
self.x = 0
struct MoveOnly(Movable, Deinitable):
var x: Int
def __init__(out self):
self.x = 0
# expected-note @below {{function declared here}}
def needs_rp[
FuncType: def () -> Int,
# expected-note @below {{constraint declared here evaluated to False, expected 'conforms_to(FuncType, RegisterPassable)'}}
](func: FuncType) -> Int where conforms_to(FuncType, RegisterPassable):
return func()
# expected-note @below {{function declared here}}
def needs_ic[
FuncType: def () -> Int,
# expected-note @below {{constraint declared here evaluated to False, expected 'conforms_to(FuncType, ImplicitlyCopyable)'}}
](func: FuncType) -> Int where conforms_to(FuncType, ImplicitlyCopyable):
return func()
def use_mem() -> Int:
var m = MemOnly()
def mem_closure() {var m} -> Int:
return m.x
# expected-error @below {{invalid call to 'needs_rp': violated constraint}}
return needs_rp(mem_closure)
def use_move() -> Int:
var m = MoveOnly()
def move_closure() {var m^} -> Int:
return m.x
# expected-error @below {{invalid call to 'needs_ic': violated constraint}}
return needs_ic(move_closure)
@@ -0,0 +1,74 @@
# ===----------------------------------------------------------------------=== #
# 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 {{the 'escaping' function effect is no longer supported}}
def escaping_effect_is_rejected(closure: def() escaping -> None):
pass
def escaping_on_nested_decl_is_rejected():
# expected-error @below {{the 'escaping' function effect is no longer supported}}
def myclosure() escaping:
pass
# COM: https://github.com/modular/mojo/issues/1223
# COM: When a runtime argument has incorrect type, nested function bodies may
# COM: still be resolved. Ensure that we don't crash when the arg is used.
struct Parametric[a: Int](Movable where False):
pass
def test_suppressed_dyn_binding_error[
x: Int
# expected-error @below {{parametric functions must not be used as arguments; pass as a parameter instead}}
# expected-note @below {{alternatively, bind its type parameters to create a concrete function}}
](pval: Parametric[x], func: def[y: Int](p: Parametric[y]) thin -> None):
def nested():
func(pval)
# ===----------------------------------------------------------------------=== #
# Closure type error message tests (MOCO-4052)
# Verify that closure types print with readable signatures, not mangled names.
# A capture is required throughout: an uncaptured nested `def` is a thin
# function, not a closure.
# ===----------------------------------------------------------------------=== #
def test_closure_to_int_error():
"""Closure assigned to Int shows a readable function signature."""
var x = 0
def my_closure(arg: Int) {x} -> Int:
return arg
# expected-error @+1 {{cannot implicitly convert 'def(arg: Int) -> Int' value to 'Int'}}
var a: Int = my_closure
def test_different_signature_closures():
"""Closures with different signatures show distinct types in error."""
var x = 0
def closure_int(arg: Int) {x} -> Int:
return arg
def closure_float(arg: Float64) {x} -> Float64:
return arg
var c = closure_int
# expected-error @+1 {{cannot implicitly convert 'def(arg: Float64) -> Float64' value to 'def(arg: Int) -> Int'}}
c = closure_float
@@ -0,0 +1,37 @@
# ===----------------------------------------------------------------------=== #
# 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 closure_holder_1() -> Int:
# expected-note @below {{nested function declared here}}
def bar(n: Int) -> Int:
if n == 0:
return 0
# expected-error @below {{recursive references to nested functions are not supported; define 'bar' at file scope}}
return n + bar(n - 1)
return bar(10)
def closure_holder_2() -> Int:
# expected-note @below {{nested function declared here}}
def foo(n: Int) -> Int:
def bar() {imm n} -> Int:
if n <= 0:
return 0
# expected-error @below {{recursive references to nested functions are not supported; define 'foo' at file scope}}
return foo(n - 1)
return bar()
return foo(10)
@@ -0,0 +1,115 @@
# ===----------------------------------------------------------------------=== #
# 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
# Regression test: declaration-time validation of explicit closure trait
# conformance (e.g. `struct Foo(def(Int) -> Int):`).
# -----
# COM: Explicit conformance fully satisfied — no diagnostics.
struct GoodCallable(def(Int) -> Int):
def __call__(self, x: Int) capturing -> Int:
return x
# -----
# COM: Missing __call__ is caught at struct declaration time.
# expected-error @below {{'MissingCall' does not implement all requirements for 'def(Bool) -> Int'}}
# expected-note @below {{required function '__call__' is not implemented}}
# expected-note @below {{def __call__(self, : Bool, /) -> Int}}
# expected-note @below {{trait 'def(Bool) -> Int' declared here}}
struct MissingCall(def(Bool) -> Int):
pass
# -----
# COM: Wrong return type is caught at struct declaration time.
# expected-error @below {{'WrongReturnType' does not implement all requirements for 'def(String) -> Int'}}
# expected-note @below {{no '__call__' candidates have type 'def(WrongReturnType, String) capturing thin -> Int'}}
# expected-note @below {{trait 'def(String) -> Int' declared here}}
struct WrongReturnType(def(String) -> Int):
# expected-note @below {{candidate declared here with type 'def(self: WrongReturnType, x: String) capturing thin -> Bool'}}
def __call__(self, x: String) capturing -> Bool:
return True
# -----
# COM: Struct satisfying two closure traits — no diagnostics.
struct TwoTraitsGood(def(Int) -> Int, def(String) -> String):
def __call__(self, x: Int) capturing -> Int:
return x
def __call__(self, x: String) capturing -> String:
return x
# -----
# COM: Second closure trait conformance fails — error names the failing trait.
# expected-error @below {{'TwoTraitsBadSecond' does not implement all requirements for 'def(Float64) -> Float64'}}
# expected-note @below {{no '__call__' candidates have type 'def(TwoTraitsBadSecond, Float64) capturing thin -> Float64'}}
# expected-note @below {{trait 'def(Float64) -> Float64' declared here}}
struct TwoTraitsBadSecond(def(Int) -> Int, def(Float64) -> Float64):
# expected-note @below {{candidate declared here with type 'def(self: TwoTraitsBadSecond, x: Int) capturing thin -> Int'}}
# expected-note @below {{.x.dtype of the first value is 'DType.float64' but the second value is 'DType.int'}}
def __call__(self, x: Int) capturing -> Int:
return x
# expected-note @below {{candidate declared here with type 'def(self: TwoTraitsBadSecond, x: Float64) capturing thin -> String'}}
def __call__(self, x: Float64) capturing -> String:
return ""
# -----
# COM: A struct that explicitly declares conformance can be passed to a
# COM: `def(Int)` parameter and called (positive, end-to-end). `capturing` is
# COM: not required on `__call__` to conform.
# expected-note @below {{function declared here}}
def call_it[F: def(Int)](func: F):
func(5)
@fieldwise_init
struct ExplicitCallable(def(Int)):
var value: Int
def __call__(self, arg: Int):
_ = arg + self.value
def test_explicit_conformance_end_to_end():
var c = ExplicitCallable(10)
call_it(c)
# -----
# COM: A struct with a compatible __call__ but no explicit `(def(Int))`
# COM: declaration is rejected — implicit conformance is not allowed.
@fieldwise_init
struct NoExplicitConformance(Movable where False):
var value: Int
def __call__(self, arg: Int):
_ = arg + self.value
def test_implicit_conformance_rejected():
var c = NoExplicitConformance(10)
# expected-error @below {{invalid call to 'call_it': value passed to 'func' cannot be converted from 'NoExplicitConformance' to 'F', argument type 'NoExplicitConformance' does not conform to trait 'def(Int) -> None'}}
call_it(c)
@@ -0,0 +1,96 @@
# ===----------------------------------------------------------------------=== #
# 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 id_simd[w: Int](v: SIMD[.uint32, w]) -> SIMD[.uint32, w]:
return v
def int32_simd[w: Int](v: SIMD[.int32, w]) -> SIMD[.int32, w]:
return v
# expected-note @+1 {{function declared here}}
def take_closure_param[
C: def[w: Int](v: SIMD[.uint32, w]) -> SIMD[.uint32, w]
]():
pass
# expected-note @+1 {{function declared here}}
def take_closure_arg[
F: def[w: Int](v: SIMD[.uint32, w]) -> SIMD[.uint32, w]
](f: F):
pass
def test_function_to_wrapper_struct():
# success: function-typed value -> concrete closure wrapper struct type.
take_closure_arg(id_simd)
# error: function-typed value with incompatible signature.
# expected-error @below {{invalid call to 'take_closure_arg'}}
take_closure_arg(int32_simd)
def test_wrapper_to_closure_param():
def wrapped_ok[
w: Int
](v: SIMD[.uint32, w]) {var} -> SIMD[.uint32, w]:
return v
def wrapped_bad[
w: Int
](v: SIMD[.int32, w]) {var} -> SIMD[.int32, w]:
return v
# success: closure-wrapper value -> closure-typed parameter.
take_closure_param[type_of(wrapped_ok)]()
# error: closure-wrapper value with incompatible signature.
# expected-error @below {{invalid call to 'take_closure_param'}}
take_closure_param[type_of(wrapped_bad)]()
def test_wrapper_to_wrapper_struct():
def wrapped_1[
w: Int
](v: SIMD[.uint32, w]) {var} -> SIMD[.uint32, w]:
return v
def wrapped_2[
w: Int
](v: SIMD[.int32, w]) {var} -> SIMD[.int32, w]:
return v
# success: closure-wrapper value -> same concrete wrapper struct type.
take_closure_arg[type_of(wrapped_1)](wrapped_1)
# error: closure-wrapper value with incompatible signature.
# expected-error @below {{invalid call to 'take_closure_arg'}}
take_closure_arg[type_of(wrapped_1)](wrapped_2)
def symbol_renamed[n: Int](x: SIMD[.uint32, n]) -> SIMD[.uint32, n]:
return x
def test_canonical_equiv_symbol_to_parameter_success():
def wrapped_renamed[
n: Int
](x: SIMD[.uint32, n]) {var} -> SIMD[.uint32, n]:
return x
# Success: closure-struct type -> parameter type implicit conversion
take_closure_param[type_of(wrapped_renamed)]()
@@ -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 -verify-diagnostics %s
from std.builtin.device_passable import DevicePassable, DeviceTypeEncoder
trait MyInterface:
def thing(self):
...
def make_closure(x: Int) -> Int:
def parametric[T: MyInterface](a: T):
# `X` is never referenced, so it's dead code the same as any other
# unreferenced comptime alias: never resolved, no diagnostic.
comptime X = A
pass
return x
struct Mem(ImplicitlyCopyable):
pass
def use(a:Mem):
pass
# COM: ambiguous captures
def aThing(x: Int) -> Int:
return x
def aThing() -> Int:
return 5
def definesClosure():
# expected-error @below {{ambiguous captured value: 'aThing'}}
def aClosure() {var aThing}:
pass
struct Bar(ImplicitlyCopyable, RegisterPassable):
var x: Int
var y: Int
def __init__(out self, *, copy: Self):
pass
# expected-note @+1 {{function declared here}}
def takeDevicePassable[T: DevicePassable](impl: T):
pass
def foo(bar: Bar) raises:
# COM: This should fail because Bar is not trivial.
def closure(number: Int) {var bar} -> Int:
return bar.x
# TODO: Rename Wrappers (MOCO-2541)
# expected-error @below {{'takeDevicePassable' parameter 'T' has 'DevicePassable' type, but value has type 'def(number: Int) -> Int'}}
takeDevicePassable[type_of(closure)](closure)
# COM: Test that a closure capturing a non trivial
# COM: type does NOT conform to TrivialRegisterPassable.
# expected-note @below {{function declared here}}
def takeTrivialRegisterPassable[T: TrivialRegisterPassable](impl: T):
pass
def testNonTrivialClosureNotTrivialRegisterPassable(bar: Bar) raises:
def closure() {var bar} -> Int:
return bar.x
# expected-error-re @below {{'{{.*}}' does not conform to trait 'TrivialRegisterPassable'}}
takeTrivialRegisterPassable(closure)
# COM: Test that a closure capturing a memory-only type does not conform to
# COM: RegisterPassable.
# expected-note @below {{function declared here}}
def takeRegisterPassable[T: RegisterPassable](impl: T):
pass
def testMemoryOnlyClosureNotRegisterPassable(mem: Mem):
def closure(number: Int) {var mem} -> Int:
_ = mem
return number
# expected-error-re @below {{'{{.*}}' does not conform to trait 'RegisterPassable'}}
takeRegisterPassable(closure)
# COM: Test that using deprecated `register_passable` effect emits a warning.
def testRegisterPassableEffectDeprecated():
# expected-warning @below {{the 'register_passable' function effect is no longer supported; use trait constraints like 'RegisterPassable & def(...) -> ...' instead}}
def closure(x: Int) register_passable -> Int:
return x
# expected-note @below {{function declared here}}
def changeIt(mut aString: String):
pass
def nestedCaptureAll(mut aString: String) raises:
def aFinalThing(x:Int) {imm}:
# expected-error @below {{invalid call to 'changeIt': value passed to mutable argument 'aString' must be mutable}}
changeIt(aString)
def aChildThing(x:Int) {var}:
changeIt(aString)
def topLevel(x: String) -> String:
return x
# expected-note @+1 {{function declared here}}
def takesClosure[T: def(Int) -> Int](cb: T, x: Int) -> Int:
return cb(x)
def useTopLevelClosure():
# expected-error @below {{invalid call to 'takesClosure': 'takesClosure' parameter 'T' has 'def(Int) -> Int' type, but value has type 'def topLevel(x: String) thin -> String'}}
# expected-note @below {{a thin function cannot bind to a closure trait; use 'type_of(topLevel)' to pass its type instead}}
takesClosure[topLevel](topLevel, 1)
# ===----------------------------------------------------------------------=== #
# Closure type mismatch errors
# ===----------------------------------------------------------------------=== #
trait Animal:
def speak(self):
...
trait Mammal(Animal):
pass
struct Dog(Mammal, Movable where False):
def speak(self):
pass
# expected-note @below {{function declared here}}
def takeClosureMammalParam[W: Mammal, C: def (x: W) -> None](impl: C):
pass
def traitConstraintMismatch[Q: Animal]():
def closure(x: Q) {var}:
x.speak()
# expected-error @below {{does not conform to trait 'def(x: W) -> None'}}
takeClosureMammalParam(closure)
def closureWrongConvention(mut x: Dog) {var}:
x.speak()
# expected-error @below {{'takeClosureMammalParam' parameter 'C' has 'def(x: W) -> None' type, but value has type 'def(mut x: Dog) -> None'}}
takeClosureMammalParam[Dog, type_of(closureWrongConvention)](closureWrongConvention)
# ===----------------------------------------------------------------------=== #
# Enforce Parameter Capture
# ===----------------------------------------------------------------------=== #
trait Coord(ImplicitlyCopyable):
pass
struct Cartesian(Coord):
var x: Int
var y: Int
var z: Int
struct Sphere(Coord):
var theta: Int
var phi: Int
# expected-note @below {{constraint declared here evaluated to False}}
# expected-note @below {{function declared here}}
def takeClosure[T: Coord, C:def() -> T](impl: C) -> T:
_ = impl()
def makeClosure[B:Int](something: Cartesian):
def closureImpl() {var} -> Cartesian:
return something
# expected-error @below {{invalid call to 'takeClosure': violated constraint}}
takeClosure[Sphere, type_of(closureImpl)](closureImpl)
# ===----------------------------------------------------------------------=== #
# Non-compatible parameter signatures disqualify conformance
# ===----------------------------------------------------------------------=== #
def _print(x: Int):
pass
# expected-note @below {{function declared here}}
def callee_no_params[
func: def() -> None,
//,
](closure: func):
closure()
def incompatible_param_signature() raises:
var x = 42
@always_inline
def my_func[param_only: Int]() {imm x}:
_print(x)
# expected-error @below {{does not conform to trait 'def() -> None'}}
callee_no_params(my_func)
# ===----------------------------------------------------------------------=== #
# Multiple default capture conventions specified
# ===----------------------------------------------------------------------=== #
def multiple_default_capture_conventions(x: Int):
# expected-error @below {{default capture convention was already specified; remove the duplicate}}
# expected-note @below {{a capture convention (like 'mut' or 'var') before the capture list sets the default for all captured variables}}
def my_closure(y: Int) {var, ref} -> Int:
return y
# ===----------------------------------------------------------------------=== #
# Incompatible capture conventions
# ===----------------------------------------------------------------------=== #
def incompatible_capture_conventions(x: Int):
# expected-error @below {{'^' requires 'var' convention; write 'var x^' to move a capture}}
def my_closure(y: Int) {ref x^} -> Int:
return y
# ===----------------------------------------------------------------------=== #
# Default capture convention violation
# ===----------------------------------------------------------------------=== #
def default_capture_convention_violation():
var y = 20
var x = 10
def my_fn() {imm, mut y}:
# Assigning to `y` work
y = 20
# expected-error @below {{expression must be mutable in assignment}}
x = 10
# ===----------------------------------------------------------------------=== #
# Capture RTP with no-read convention
# ===----------------------------------------------------------------------=== #
def capture_RTP(x : Int) :
# expected-error @below{{register passible value 'x' can not be captured by 'mut'. Do you mean 'imm'?}}
def my_func() {mut x}:
pass
# ===----------------------------------------------------------------------=== #
# By-copy / by-move unified closure captures still require a conforming type
# when no scope assumption refines the generic bound (MOCO-4229 regression
# guard: refinement must not swallow this diagnostic for a truly unbound T).
# ===----------------------------------------------------------------------=== #
trait NotImplicitlyCopyable:
pass
# expected-error @below {{value of type 'T' cannot be implicitly copied, it does not conform to 'ImplicitlyCopyable'}}
def capture_by_copy_no_refinement[T: NotImplicitlyCopyable](z: T):
# expected-error @below {{cannot capture z by copy because it is not copyable.}}
def f() {var z}:
_ = z
f()
trait NotMovable:
pass
def capture_by_move_no_refinement[T: NotMovable](var z: T):
# expected-error @below {{Cannot capture z by move because the type is not movable}}
def h() {var z^}:
_ = z
h()
# ===----------------------------------------------------------------------=== #
# A closure capturing a DevicePassable value by reference is not DevicePassable
# ===----------------------------------------------------------------------=== #
# COM: A by-reference capture stores a host pointer (LIT::RefType) as its
# COM: storage field, so the closure cannot be device-encoded even though the
# COM: capture's type is itself DevicePassable (MOCO-4045). .
@fieldwise_init
struct RegPassableDevice(
DevicePassable, ImplicitlyCopyable, TrivialRegisterPassable
):
comptime device_type: AnyType = Int
var value: Int
def _to_device_type(
self, mut encoder: Some[DeviceTypeEncoder], target: MutOpaquePointer[_]
):
encoder.encode(self.value, target)
@staticmethod
def get_type_name() -> String:
return "RegPassableDevice"
# expected-note @below {{function declared here}}
def takeDevicePassableByRef[T: DevicePassable](impl: T):
pass
def capture_device_passable_by_reference(value: RegPassableDevice) raises:
def closure(argument: Int) {imm value} -> Int:
return argument + value.value
# expected-error-re @below {{'{{.*}}' does not conform to trait 'DevicePassable'}}
takeDevicePassableByRef(closure)
@fieldwise_init
struct MemType:
pass
# expected-note @below {{function declared here}}
def apply(f: Some[RegisterPassable & def() -> None]):
pass
def main():
var t = MemType()
def func() {var t^}:
pass
# expected-error @below {{invalid call to 'apply': value passed to 'f' cannot be converted from 'def() -> None' to 'T', argument type 'def() -> None' does not conform to trait 'def() -> None & RegisterPassable'}}
apply(func)
@@ -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 -verify-diagnostics %s
def use(a: Int):
pass
def use(a: StaticString):
pass
def test():
# True dead code - check for warnings
# expected-warning @+1 {{unreachable code on right side of 'False and ...'}}
use(0 and 0)
# expected-warning @+1 {{unreachable code on right side of 'False and ...'}}
use(0 and 1)
# expected-warning @+1 {{unreachable code on right side of 'True or ...'}}
use(1 or 0)
# expected-warning @+1 {{unreachable code on right side of 'True or ...'}}
use(1 or 1)
# expected-warning @+1 {{right hand side expression of 'if True' is dead}}
use(1 if 1 else 0)
# expected-warning @+1 {{left hand side expression of 'if False' is dead}}
use(1 if 0 else 0)
# expected-warning @+1 {{'if' condition always evaluates to 'False'; 'if' branch is unreachable}}
if 0:
use("dead")
# expected-warning @+1 {{'if' condition always evaluates to 'False'; 'if' branch is unreachable}}
elif 0:
use("dead elif")
# expected-warning @+1 {{'if' condition always evaluates to 'True'; 'else' branch is unreachable}}
elif 1:
use("live elif")
else:
use("dead else")
# No dead user code, but still constant branch conditions
# expected-warning @+1 {{constant value on left side of 'False or ...'}}
use(0 or 0)
# expected-warning @+1 {{constant value on left side of 'False or ...'}}
use(0 or 1)
# expected-warning @+1 {{constant value on left side of 'True and ...'}}
use(1 and 0)
# expected-warning @+1 {{constant value on left side of 'True and ...'}}
use(1 and 1)
@@ -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,246 @@
# ===----------------------------------------------------------------------=== #
# 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
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
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,268 @@
# ===----------------------------------------------------------------------=== #
# 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 {{'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 {{'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 {{'__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
# 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,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,172 @@
# ===----------------------------------------------------------------------=== #
# 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
# 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,342 @@
# ===----------------------------------------------------------------------=== #
# 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
# 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.elif
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.elif
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.elif
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,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,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,32 @@
# ===----------------------------------------------------------------------=== #
# 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
# Basic tests for when multiple parent traits define a associated alias with
# conflicting signature and no user-provided value in the child struct.
trait B:
# expected-note@below{{conflicting implementation from trait B here}}
comptime a: Int = 1
trait A:
# expected-note@below{{original default implementation from trait A here}}
comptime a: Int = 2
# expected-error@below{{trait member 'a' has conflicting default implementations in B and A; you must implement it manually}}
struct Foo(A, B, Movable where False):
pass
@@ -0,0 +1,100 @@
# ===----------------------------------------------------------------------=== #
# 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
# Basic tests for when multiple parent traits define a function with
# conflicting signature and no override in the child struct.
trait Foo1:
# expected-note @+1 {{original default implementation from trait 'Foo1' here}}
def foo(self) -> Int:
return 1
trait Foo2(Foo1):
# expected-note @+1 {{conflicting implementation from trait 'Foo2' here}}
def foo(self) -> Int:
return 2
trait Foo3(Foo1):
# expected-note @+1 {{conflicting implementation from trait 'Foo3' here}}
def foo(self) -> Int:
return 3
@fieldwise_init
# expected-error @+2 {{trait method requirement 'foo' has conflicting default implementations in 'Foo1' and 'Foo2'; you must implement it manually}}
# expected-error @+1 {{trait method requirement 'foo' has conflicting default implementations in 'Foo1' and 'Foo3'; you must implement it manually}}
struct Foo(Foo2, Foo3, Movable where False):
pass
trait AA1:
comptime X: ImplicitlyCopyable
# expected-note @+1 {{original default implementation from trait 'AA1' here}}
def zork(self, x: Self.X) -> Self.X:
return x
trait AA2:
comptime X: ImplicitlyCopyable
# expected-note @+1 {{conflicting implementation from trait 'AA2' here}}
def zork(self, x: Self.X) -> Self.X:
return x
@fieldwise_init
# expected-error @+1 {{trait method requirement 'zork' has conflicting default implementations in 'AA1' and 'AA2'; you must implement it manually}}
struct Bar(AA1, AA2, Movable where False):
comptime X: ImplicitlyCopyable = Int
trait WithAsyncMethod:
# expected-error @+1 {{async defaulted trait methods are not supported; remove the method or remove 'async'}}
async def async_default_method(self) -> Int:
return 42
# TODO: Should the 'original' implementation not be FooC here? It's ordering
# alphabetically.
@fieldwise_init
struct RP(TrivialRegisterPassable):
pass
trait FooC:
# expected-note @+1 {{conflicting implementation from trait 'FooC' here}}
def foo(self) -> RP:
return RP()
def bar(self) -> RP:
return RP()
trait FooB(FooC):
# expected-note @+1 {{original default implementation from trait 'FooB' here}}
def foo(self) -> RP:
return RP()
def bar(self) -> RP:
return RP()
# expected-error @+1 {{trait method requirement 'foo' has conflicting default implementations in 'FooB' and 'FooC'; you must implement it manually}}
struct FooActual(FooB, Movable where False):
pass
@@ -0,0 +1,29 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
# RUN: %parse-mojo-isolated -verify-diagnostics %s
def test1():
# expected-error @below {{invalid MLIR attribute: `#kgen.deferred` can only be used for non-typed attributes}}
# expected-note @below {{attempting to parse: '#kgen.deferred 0 : index'}}
_ = __mlir_attr.`#kgen.deferred 0 : index`
struct DType(Movable where False):
comptime type = __mlir_type.`!kgen.dtype`
var value: Self.type
def test3(x: __mlir_type.`!kgen.struct<(!kgen.scalar<f32>)>`):
# expected-error @+1 {{element index 1 out of bounds (>=1)}}
_ = __mlir_op.`kgen.struct.extract`[_type = __mlir_type.`!kgen.scalar<f32>`, index=__mlir_attr.`1:index`](x)
@@ -0,0 +1,32 @@
# ===----------------------------------------------------------------------=== #
# 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
@export
def use_mlir_attr_warning_subscript(a: Int, b: Int) abi("Mojo") -> Bool:
# expected-warning @+2 {{trivially constructable attribute. Use `__mlir_attr` instead.}}
var res = __mlir_op.`index.cmp`[
pred=__mlir_deferred_attr[`#index.cmp_predicate<sle>`]
](a, b)
return res
@export
def use_mlir_attr_warning_backticks(a: Int, b: Int) abi("Mojo") -> Bool:
# expected-warning @+2 {{trivially constructable attribute. Use `__mlir_attr` instead}}
var res = __mlir_op.`index.cmp`[
pred=__mlir_deferred_attr.`#index.cmp_predicate<sle>`
](a, b)
return res
@@ -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 %s -verify-diagnostics
# When all parts of __mlir_deferred_type are trivially constructable (no
# unresolved parameters), the compiler emits a warning suggesting __mlir_type.
# expected-warning @+2 {{trivially constructable type. Use `__mlir_type` instead.}}
@always_inline
def trivially_constructable_return_type() -> __mlir_deferred_type[
`!llvm.array<4 x f32>`
]:
# expected-warning @+2 {{trivially constructable type. Use `__mlir_type` instead.}}
return __mlir_op.`llvm.mlir.undef`[
_type = __mlir_deferred_type[`!llvm.array<4 x f32>`]
]()
@@ -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.
# ===----------------------------------------------------------------------=== #
# RUN: %parse-mojo-isolated -o /dev/null -mojo-diagnose-missing-doc-strings -verify-diagnostics %s
# FileModuleOp is located at line 1, col 1 of the buffer, so the diagnostic
# fires there. @-16 counts back from this line to line 1.
# expected-warning @-16 {{public module '__init__' is missing a doc string}}
# '__init__' is treated as a public module even though its name begins with '_':
# it is the public package initializer, not a private symbol.
# This file intentionally has no module-level doc string.
@@ -0,0 +1,468 @@
# ===----------------------------------------------------------------------=== #
# 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 doc string validation diagnostics."""
# RUN: %parse-mojo-isolated -o /dev/null -mojo-diagnose-missing-doc-strings -verify-diagnostics %s
# expected-warning @below {{public symbol 'ArgStruct' is missing a doc string}}
struct ArgStruct(Movable where False):
pass
struct _ParamStruct_Private_Missing[_type: __mlir_type.`!kgen.dtype`](Movable where False):
"""This is a private struct doc string.
It doesn't need to include a `Parameters:` section.
"""
pass
# expected-warning @below {{struct takes parameters, but has no 'Parameters' in doc string}}
struct ParamStruct_Missing[_type: __mlir_type.`!kgen.dtype`](Movable where False):
"""This doc string is missing a `Parameters:` section."""
pass
struct ParamStruct_Invalid[_type: __mlir_type.`!kgen.dtype`](Movable where False):
"""This is a class summary.
# expected-warning-re @below {{parameter '{{.*}}_type' is not documented}}
Parameters:
invalid_param: This is an invalid parameter.
# expected-warning @above {{unknown parameter 'invalid_param' in doc string}}
"""
pass
struct ParamStruct_Duplicates[_type: __mlir_type.`!kgen.dtype`](Movable where False):
"""This is a class summary.
# expected-note @below {{see previous definition here}}
Parameters:
_type: Summary.
_type: Summary.
# expected-warning @above {{duplicate parameter '_type' in doc string}}
# expected-warning @below {{duplicate 'Parameters' section found in doc string}}
Parameters:
_type: Summary.
"""
pass
struct ParamStruct_Order[
param1: __mlir_type.`!kgen.dtype`, param2: __mlir_type.`!kgen.dtype`
](Movable where False):
"""This is a class summary.
Parameters:
param2: Summary.
param1: Summary.
"""
# expected-warning @-4 {{'param2' is defined at index 1, but specified in doc string at index 0}}
pass
struct StructWithMissingMethod(Movable where False):
"""This defines methods with missing doc strings."""
# expected-warning @below {{public symbol 'method_with_missing_doc_string' is missing a doc string}}
def method_with_missing_doc_string(self):
pass
def _private_method_with_no_doc_string(self):
pass
# expected-warning @below {{public symbol '__init__' is missing a doc string}}
def __init__(out self):
pass
# expected-warning @below {{public symbol 'fn_missing_doc_string' is missing a doc string}}
def fn_missing_doc_string():
pass
def _fn_private_no_doc_string():
pass
def fn_poor_style():
"""this summary should be capitalized and end with a period"""
# expected-warning @above {{doc string summary should begin with a capital letter or non-alpha character, but this begins with 't'}}
# expected-warning @above {{doc string summary should end with a period '.', exclamation mark '!', question mark '?', or backtick '`', but this ends with 'd'}}
pass
def _fn_private_args_missing(arg: ArgStruct):
"""This is a private function doc string.
It doesn't need to include an `Args:` section.
"""
pass
# expected-warning @below {{function takes arguments, but has no 'Args' in doc string}}
def fn_args_missing(arg: ArgStruct):
"""This doc string is missing an `Args:` section."""
return
def fn_args_invalid(arg: ArgStruct):
"""This is a function summary.
# expected-warning @below {{argument 'arg' is not documented}}
Args:
unknown_arg: This is an argument.
# expected-warning @above {{unknown argument 'unknown_arg' in doc string}}
"""
return
def fn_args_overindent(arg: ArgStruct):
"""This is a function summary.
Description.
# expected-warning @below {{section tag 'Args' is overindented}}
Args:
arg: This is an argument.
"""
return
def fn_args_duplicates(arg: ArgStruct):
"""This is a function summary.
# expected-note @below {{see previous definition here}}
Args:
arg: This is an argument.
arg: This is an argument.
# expected-warning @above {{duplicate argument 'arg' in doc string}}
# expected-warning @below {{duplicate 'Args' section found in doc string}}
Args:
arg: This is an argument.
"""
return
def fn_args_order(arg: ArgStruct, arg2: ArgStruct):
"""This is a function summary.
Args:
arg2: This is an argument.
arg: This is an argument.
"""
# expected-warning @-3 {{'arg2' is defined at index 1, but specified in doc string at index 0}}
return
def fn_args_empty(arg: ArgStruct, arg2: ArgStruct):
"""This function contains empty argument descriptions.
Args:
arg:
arg2:
"""
# expected-warning @-3 {{'arg' does not have a description}}
# expected-warning @-3 {{'arg2' does not have a description}}
pass
def fn_args_poor_style(arg: ArgStruct, arg2: ArgStruct):
"""This function contains arguments with poor style.
Args:
arg: `arg` starts with a valid character but doesn't end with a period
arg2: this should start with a capital letter.
"""
# expected-warning @-3 {{'arg' description should end with a period '.', exclamation mark '!', question mark '?', or backtick '`', but this ends with 'd'}}
# expected-warning @-3 {{'arg2' description should begin with a capital letter or non-alpha character, but this begins with 't'}}
pass
def fn_args_return():
"""This is a function summary.
# expected-warning @below {{unexpected 'Returns' in doc string for function with no results}}
# expected-note @below {{see previous definition here}}
Returns:
This returns nothing.
# expected-warning @below {{duplicate 'Returns' section found in doc string}}
Returns:
This returns nothing.
"""
return
def fn_raises():
"""This is a function summary.
# expected-warning @below {{unexpected 'Raises' in doc string for function that does not throw}}
# expected-note @below {{see previous definition here}}
Raises:
This raises nothing.
# expected-warning @below {{duplicate 'Raises' section found in doc string}}
Raises:
This raises nothing.
"""
return
# expected-warning @below {{function can throw errors, but has no 'Raises' in doc string}}
def fn_missing_raises_section() raises:
"""This doc string is missing a `Raises:` section."""
pass
# expected-warning @below {{function has results, but has no 'Returns' in doc string}}
def fn_args_missing_return() -> Int:
"""This doc string is missing a `Returns:` section."""
return 0
def fn_returns_section_empty() -> Int:
"""This doc string includes a `Returns:` section, but it's empty.
# expected-warning @below {{'Returns' section is empty}}
Returns:
"""
return 0
def fn_returns_section_poor_style() -> Int:
"""This doc string has a `Returns:` section with poor style.
Returns:
doesn't start with a capital letter and doesn't end with punctuation
"""
# expected-warning @-2 {{section body should begin with a capital letter or non-alpha character, but this begins with 'd'}}
# expected-warning @-3 {{section body should end with a period '.', exclamation mark '!', question mark '?', or backtick '`', but this ends with 'n'}}
return 0
def fn_nested_fn():
"""This is a function that defines a nested function.
The nested function does not include a doc string, but it should not be
reported as invalid.
"""
def nested_fn():
pass
return
def fn_unified_thin_closure():
"""This function defines a thin unified closure (no captures).
The closure is lifted to file scope during compilation, but docstring
rules must not be enforced on it.
"""
def thin_closure(x: Int) -> Int:
return x
struct Error(Movable where False):
"""Error type stub to allow decoupling from the builtins."""
pass
def fn_raises_with_return_type(x: Int) raises -> Int:
"""This is a function that raises, with an explicit return type.
Because it raises, it implicitly has a memory-only `__result__` argument.
However, this doc string should not document this hidden argument.
Args:
x: An explicit argument.
Returns:
`0`.
Raises:
Exception description goes here.
"""
return 0
def def_implicit_return_type(x: Int) raises:
"""This is a `def` function with no explicit return type.
Args:
x: An explicit argument.
Raises:
Exception: if an error occurs.
"""
pass
# ===----------------------------------------------------------------------=== #
# Alias doc string validation
# ===----------------------------------------------------------------------=== #
# expected-warning-re @below {{public symbol 'AliasWithParams_MissingDocString{{.*}}' is missing a doc string}}
comptime AliasWithParams_MissingDocString[T: AnyType] = T
comptime _AliasWithParams_Private[T: AnyType] = T
# expected-warning @below {{comptime value has parameters, but has no 'Parameters' in doc string}}
comptime AliasWithParams_MissingParamsSection[T: AnyType] = T
"""This alias doc string is missing a Parameters section."""
comptime AliasWithParams_InvalidParam[T: AnyType] = T
"""This alias has an invalid parameter documented.
# expected-warning-re @below {{parameter '{{.*}}T' is not documented}}
Parameters:
invalid_param: This is an invalid parameter.
# expected-warning @above {{unknown parameter 'invalid_param' in doc string}}
"""
comptime AliasWithParams_Valid[T: AnyType] = T
"""This alias has valid parameter documentation.
Parameters:
T: The type parameter.
"""
# expected-warning @+5 {{'U' is defined at index 1, but specified in doc string at index 0}}
comptime AliasWithMultipleParams_Order[T: AnyType, U: AnyType] = T
"""This alias has parameters in wrong order.
Parameters:
U: Second parameter documented first.
T: First parameter documented second.
"""
# Test that autoparams (compiler-generated parameters with mangled names like
# `a`1`) are correctly ignored in docstring validation. When doing partial
# binding, the compiler generates autoparams for the unbound parameters.
struct _AutoParamTest[
a: __mlir_type.`!kgen.dtype`, b: __mlir_type.`!kgen.dtype`
](Movable where False):
pass
def _fn_with_params[x: Int](s: _AutoParamTest):
pass
# Partial binding generates autoparams like `a`1`, `b`2` for the struct's params.
# These mangled names should NOT require documentation.
comptime AliasWithAutoParams = _fn_with_params[1]
"""This alias has compiler-generated autoparams that should be ignored."""
# ===----------------------------------------------------------------------=== #
# @doc_hidden suppresses missing doc string warnings (MOTO-957)
# ===----------------------------------------------------------------------=== #
# @doc_hidden on a comptime alias suppresses the missing doc string warning.
# (MOTO-957: previously @doc_hidden caused a compiler error on aliases)
@doc_hidden
comptime doc_hidden_alias = 42
# @doc_hidden on a struct field suppresses the missing doc string warning.
# (MOTO-957: previously @doc_hidden caused a compiler error on struct fields)
struct StructWithDocHiddenField(Movable where False):
"""A struct testing @doc_hidden on fields."""
@doc_hidden
var hidden_field: Int
# ===----------------------------------------------------------------------=== #
# Inferred parameter doc string validation (MOTO-485)
# ===----------------------------------------------------------------------=== #
# Inferred parameters (before //) do not require documentation.
# No warning should be emitted for undocumented inferred param 'T'.
def fn_with_inferred_param[T: AnyType, //, U: AnyType]():
"""This function has both inferred and regular parameters.
Parameters:
U: The user-visible parameter.
"""
pass
# Inferred parameters may also be documented without triggering "unknown
# parameter" warnings, since they appear in the generated API docs.
def fn_with_documented_inferred_param[T: AnyType, //, U: AnyType]():
"""This function documents both its inferred and regular parameters.
Parameters:
T: The inferred parameter — documenting it is valid but not required.
U: The user-visible parameter.
"""
pass
# When all compile-time parameters are inferred, no 'Parameters' section is needed.
def fn_with_only_inferred_params[T: AnyType, //](arg: ArgStruct):
"""This function's only compile-time parameters are inferred.
Args:
arg: An argument.
"""
pass
# Structs: inferred parameters do not require documentation.
struct StructWithInferredParam[T: AnyType, //, U: AnyType](Movable where False):
"""A struct with an inferred and a regular parameter.
Parameters:
U: The user-visible parameter.
"""
pass
# Aliases: inferred parameters do not require documentation.
comptime AliasWithInferredParam[T: AnyType, //, U: AnyType] = U
"""An alias with an inferred and a regular parameter.
Parameters:
U: The user-visible parameter.
"""
# When all compile-time parameters are inferred, no 'Parameters' section is needed.
comptime AliasWithOnlyInferredParams[T: AnyType, //] = T
"""This alias's only compile-time parameter is inferred."""
@@ -0,0 +1,26 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
# RUN: %parse-mojo-isolated -o /dev/null -mojo-diagnose-missing-doc-strings -verify-diagnostics %s
# FileModuleOp is located at line 1, col 1 of the buffer, so the diagnostic
# fires there. @-16 counts back from this line to line 1.
# expected-warning @-16 {{public module 'parser_doc_module_errors' is missing a doc string}}
# A public module without a doc string should raise a diagnostic.
# This file intentionally has no module-level doc string.
struct ArgStruct(Movable where False):
"""A stub type for arguments."""
pass
@@ -0,0 +1,324 @@
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
# RUN: %parse-mojo-isolated %s -mlir-print-debuginfo | FileCheck %s
# RUN: %parse-mojo-isolated %s -mlir-print-debuginfo | kgen-opt -lower-semantic-cf -check-lifetimes -verify-diagnostics
from std.builtin._coroutine import Coroutine, RaisingCoroutine, AnyCoroutine
@explicit_destroy("Must use consume!")
struct EmptyExplicit(Deinitable where False, Movable where False):
def __init__(out self):
pass
def consume(deinit self):
pass
def errorExample():
# expected-error @below {{Must use consume!}}
_ = EmptyExplicit()
@explicit_destroy("Must use consume!")
struct DeinitableContainerOfExplicitWithAutoDel(
Deinitable where False, Movable where False
):
var m: EmptyExplicit
def __init__(out self):
self.m = EmptyExplicit()
def testDeinitableContainerOfExplicitWithAutoDel():
# expected-error @below {{Must use consume!}}
_ = DeinitableContainerOfExplicitWithAutoDel()
struct DeinitableContainerOfExplicitWithIncompleteDel(Movable where False):
var m: EmptyExplicit
def __init__(out self):
self.m = EmptyExplicit()
# expected-error @below {{Must use consume!}}
def __deinit__(deinit self):
pass
# CHECK-LABEL: @"test_any_type_error
# expected-error @below {{unhandled explicitly destroyed type 'AnyType'}}
# expected-note @below {{consider adding trait conformance to Deinitable}}
def test_any_type_error[T: AnyType](var x: T):
pass
# TODO(MOCO-2363): re-enable the test below
#
# # TODO(MOCO-1468): Require error message for @explicit_destroy
# @explicit_destroy
# trait LinearCopyable(ImplicitlyCopyable):
# pass
# # C_HECK-LABEL: @"receiveLinearCopyable
# # e_xpected-error @below {{Unhandled explicit_destroy type LinearCopyable}}
# def receiveLinearCopyable[T: LinearCopyable](var x: T):
# pass
# @explicit_destroy
# struct LinearCopyableStruct(LinearCopyable):
# def __init__(out self, *, copy: Self):
# pass
# # C_HECK-LABEL: @"upcastLinearCopyable
# def upcastLinearCopyable(var x: LinearCopyableStruct):
# receiveLinearCopyable(x)
# CHECK-LABEL: lit.fn @"callsWith
def callsWith():
# expected-error @below {{type 'Coroutine' does not conform to 'Deinitable' and must be explicitly destroy}}
_ = testAsyncVoid()
# CHECK-NOT: lit.call {{.*}}__deinit__
# CHECK-LABEL: lit.fn @"testAsyncVoid
async def testAsyncVoid():
pass
# CHECK-LABEL: lit.struct.decl @ExplicitWithDeinit
# MOCO-2787 - Linear types do not error if they contain an explicit deinit
@explicit_destroy("must use __deinit__() explicitly")
struct ExplicitWithDeinit(Deinitable where False, Movable where False):
def __init__(out self):
pass
# Presence of a deinit shouldn't override @explicit_destroy.
def __deinit__(deinit self):
pass
def method(self):
pass
def testExplicitWithDeinit():
var a = ExplicitWithDeinit()
a.method()
a^.__deinit__() # ok
var b = ExplicitWithDeinit()
b.method() # expected-error {{'b' abandoned without being explicitly destroyed: must use __deinit__() explicitly}}
# This comes from stubs library.
# CHECK-LABEL: lit.struct.decl @Coroutine
# CHECK-NOT: destructor :!lit.generator
# ===----------------------------------------------------------------------=== #
# Trait with custom @explicit_destroy error message
# ===----------------------------------------------------------------------=== #
# Trait without @explicit_destroy and without Deinitable
trait PlainTrait:
def do_something(self):
...
# A plain trait (no @explicit_destroy, no Deinitable) is linear and
# uses the synthesized default message.
trait LinearNoMessage:
def destroy_no_msg(deinit self):
...
@explicit_destroy("Use `destroy()` method.")
trait ExplicitDestroyWithMessage:
def destroy(deinit self):
...
# Test: Plain trait without @explicit_destroy
# expected-error @below {{unhandled explicitly destroyed type 'PlainTrait'}}
# expected-note @below {{consider adding trait conformance to Deinitable}}
def take_plain_trait[T: PlainTrait](var value: T):
pass
# Test: Plain linear trait with no custom message uses the default message
# expected-error @below {{unhandled explicitly destroyed type 'LinearNoMessage'}}
# expected-note @below {{consider adding trait conformance to Deinitable}}
def take_generic_linear_no_message[T: LinearNoMessage](var value: T):
pass
# Test: Trait with @explicit_destroy("...") custom message
def take_generic_linear_with_message[
T: ExplicitDestroyWithMessage
# expected-error @below {{Use `destroy()` method.}}
# expected-note @below {{consider adding trait conformance to Deinitable}}
](var value: T):
pass
# ===----------------------------------------------------------------------=== #
# Trait composition with @explicit_destroy
# ===----------------------------------------------------------------------=== #
@explicit_destroy("Use custom_foo_destroy().")
trait LinearFoo:
def custom_foo_destroy(deinit self):
...
@explicit_destroy("Use custom_bar_destroy().")
trait LinearBar:
def custom_bar_destroy(deinit self):
...
# Test: First trait has custom message - uses that message
# expected-error @below {{Use custom_bar_destroy().}}
# expected-note @below {{consider adding trait conformance to Deinitable}}
def take_foo_and_bar[T: LinearFoo & LinearBar](var value: T):
pass
# Test: Composing a default-message linear trait with a custom-message one -
# the trait carrying an explicit @explicit_destroy message provides the
# diagnostic.
# expected-error @below {{Use custom_bar_destroy().}}
# expected-note @below {{consider adding trait conformance to Deinitable}}
def take_no_msg_first[T: LinearNoMessage & LinearBar](var value: T):
pass
# ===----------------------------------------------------------------------=== #
# @explicit_destroy("") on linear traits (valid but poor form)
# ===----------------------------------------------------------------------=== #
# Test: Empty string message is valid on a linear trait (trait without
# Deinitable). The empty message will be used as the error.
@explicit_destroy("")
trait LinearWithEmptyMessage:
def consume(deinit self):
...
# expected-error @below {{abandoned without being explicitly destroyed: }}
# expected-note @below {{consider adding trait conformance to Deinitable}}
def take_linear_empty_message[T: LinearWithEmptyMessage](var value: T):
pass
# ===----------------------------------------------------------------------=== #
# Conditional Deinitable without @explicit_destroy
# ===----------------------------------------------------------------------=== #
# A struct may conditionally conform to Deinitable via a where-clause
# without using @explicit_destroy. When the where-clause is not satisfied for a
# given instantiation the type is linear, and the compiler emits a synthesized
# default linear-type error message.
struct CondDeinitableDefault[cond: Bool](
Deinitable where cond, Movable where False
):
def __init__(out self):
pass
def testConditionalDeinitableDefaultMessage():
# cond=True satisfies the where-clause, no error.
_ = CondDeinitableDefault[True]()
# expected-error @below {{abandoned without being explicitly destroyed: type 'CondDeinitableDefault' does not conditionally conform to 'Deinitable' for these parameters}}
_ = CondDeinitableDefault[False]()
# ===----------------------------------------------------------------------=== #
# `Deinitable where False` opts out of implicit deletability (MOCO-4235)
# ===----------------------------------------------------------------------=== #
# An unsatisfiable where-clause opts the struct out of implicit deletability
# entirely. A default linear-type error message is used when no custom one is
# provided by `@explicit_destroy`.
struct WhereFalseLinear(Deinitable where False, Movable where False):
def __init__(out self):
pass
def testWhereFalseLinear():
# expected-error @below {{abandoned without being explicitly destroyed: type 'WhereFalseLinear' does not conform to 'Deinitable' and must be explicitly destroyed}}
_ = WhereFalseLinear()
# A custom message via @explicit_destroy is used in preference to the default.
@explicit_destroy("use consume()")
struct WhereFalseCustom(Deinitable where False, Movable where False):
def __init__(out self):
pass
def testWhereFalseCustomMessage():
# expected-error @below {{abandoned without being explicitly destroyed: use consume()}}
_ = WhereFalseCustom()
# A conditional Deinitable slot that the struct's own where-clause
# renders unsatisfiable (`where not (n > 0)` under `where n > 0`) is an opt-out
# indistinguishable from the literal `where False` above: for any instantiable
# `n`, the struct is linear and reports the *same* default message. This is
# invariant 2 (semantic == literal unsatisfiability) applied to the message
# text, not just to synthesis.
struct ContradictedLinear[n: Int](
Deinitable where not (n > 0), Movable where False
) where n > 0:
def __init__(out self):
pass
def testContradictedLinear():
# expected-error @below {{abandoned without being explicitly destroyed: type 'ContradictedLinear' does not conform to 'Deinitable' and must be explicitly destroyed}}
_ = ContradictedLinear[1]()
# ===----------------------------------------------------------------------=== #
# Indirect mutable assignment of a linear type
# ===----------------------------------------------------------------------=== #
# An indirect mutable assignment `ptr[] = linear^` overwrites the value at
# the reference target, which must first be implicitly destroyed. When the
# target's type is linear the reference has no user-visible name, so the
# diagnostic describes the abandoned value generically and relies on the
# source location to point at the offending expression.
@explicit_destroy("use consume()")
struct IndirectAssignLinear(Movable, Deinitable where False):
def __init__(out self):
pass
def testIndirectAssignLinear(p: UnsafePointer[IndirectAssignLinear, MutAnyOrigin]):
# expected-error @+1 {{value abandoned without being explicitly destroyed: use consume()}}
p[] = IndirectAssignLinear()^
Loaded 100 of 1301 files, more files were not shown because too many files have changed in this diff. Show more