Baseline: tree as shared

This commit is contained in:
alexm committed 2026-10-05 03:03:38 +00:00
commit 31f2fb8a5a
1679 files changed
+1024562

No files matched your search

+100
View File
@@ -0,0 +1,100 @@
# EditorConfig: https://editorconfig.org
# In VS Code, install the "EditorConfig for VS Code" extension (EditorConfig.EditorConfig).
root = true
# Defaults for every file
[*]
charset = utf-8
end_of_line = lf
indent_style = space
indent_size = 4
insert_final_newline = true
trim_trailing_whitespace = true
# Python
[*.{py,pyi}]
indent_size = 4
max_line_length = 88
# Mojo (`mojo format` is Black-style, 88 columns; the fire emoji extension is also valid)
[*.{mojo,🔥}]
indent_size = 4
max_line_length = 88
# Rust (rustfmt defaults: 4 spaces, 100 columns)
[*.rs]
indent_size = 4
max_line_length = 100
# Cargo manifests and rustfmt config
[{Cargo.toml,Cargo.lock,rustfmt.toml,.rustfmt.toml,clippy.toml}]
indent_size = 4
# Mojo project manifest
[{mojoproject.toml,pixi.toml,pixi.lock}]
indent_size = 4
# YAML
[*.{yml,yaml}]
indent_size = 2
# JSON and friends
[*.{json,jsonc,json5}]
indent_size = 2
# Web
[*.{js,jsx,mjs,cjs,ts,tsx,css,scss,less,html,vue,svelte}]
indent_size = 2
# Config formats
[*.{toml,ini,cfg}]
indent_size = 4
[*.xml]
indent_size = 2
# Markdown: trailing spaces are significant (hard line breaks)
[*.{md,markdown}]
indent_size = 2
trim_trailing_whitespace = false
# typst
[*.{typ}]
indent_size = 4
trim_trailing_whitespace = false
# Shell scripts
[*.{sh,bash,zsh}]
indent_size = 2
# Makefiles require tabs
[{Makefile,makefile,*.mk}]
indent_style = tab
# Go uses tabs
[*.go]
indent_style = tab
# Windows-only scripts need CRLF
[*.{bat,cmd,ps1}]
end_of_line = crlf
# Dockerfiles
[{Dockerfile,Dockerfile.*,*.dockerfile}]
indent_size = 4
# Terraform
[*.{tf,tfvars,hcl}]
indent_size = 2
# Don't touch these
[LICENSE*]
insert_final_newline = false
[*.{diff,patch}]
trim_trailing_whitespace = false
[*.min.{js,css}]
insert_final_newline = unset
trim_trailing_whitespace = unset
+2
View File
@@ -0,0 +1,2 @@
# SCM syntax highlighting & preventing 3-way merges
pixi.lock merge=binary linguist-language=YAML linguist-generated=true -diff
+75
View File
@@ -0,0 +1,75 @@
# Programming+ on Gitea Actions, with a runner that has no container image:
# the act_runner runs jobs directly on the droplet's shell ("host mode").
#
# Runner setup, once, on the droplet (docs/deploy.md):
# - node >= 20, git, rsync installed; a `deploy` user that can write /srv/www
# - act_runner registered with the host-mode label this file's `runs-on` names:
# act_runner register --instance https://git.example --token ... --labels "quarto-deploy:host"
# (the `:host` suffix is what makes jobs run on the machine instead of in docker)
#
# Every push and pull request builds and tests. A push to main also publishes
# the site to /srv/www/<slug> as an atomic release (scripts/deploy.sh).
#
# Repository → Settings → Actions → Variables (all optional):
# SITE_SLUG the directory under /srv/www (defaults to the repository name)
# SITE_URL e.g. https://pplus.scient.ing, turns on the smoke test
name: Build, test, deploy
on:
push:
branches: [main]
pull_request:
workflow_dispatch:
concurrency:
group: deploy-${{ gitea.ref }}
cancel-in-progress: true
jobs:
site:
# The host-mode label from the runner registration. Jobs run as the
# runner's user, in a fresh working directory, with the host's node.
runs-on: quarto-deploy
steps:
# actions/checkout needs node on the host, which the job needs anyway.
- uses: actions/checkout@v4
- name: Toolchain on the host
run: |
node --version
npm --version
git --version
command -v rsync >/dev/null || echo "rsync missing: local deploys fall back to cp, SSH deploys need it"
- run: npm ci
- run: npm test
# The same check as `pixi run mojo-status-strict`: offline, from the stored godbolt answers.
- name: Our Mojo programs pass
run: |
if command -v python3 >/dev/null; then python3 scripts/mojo/corpus.py status --strict
else echo "python3 missing: corpus status skipped"; fi
- name: Assemble the site
run: scripts/assemble.sh
env:
GITHUB_SHA: ${{ gitea.sha }}
- name: Publish to /srv/www
if: gitea.event_name != 'pull_request' && gitea.ref == 'refs/heads/main'
env:
SLUG: ${{ vars.SITE_SLUG || gitea.event.repository.name }}
GITHUB_SHA: ${{ gitea.sha }}
run: scripts/deploy.sh "$SLUG"
- name: Smoke test
if: gitea.event_name != 'pull_request' && gitea.ref == 'refs/heads/main' && vars.SITE_URL != ''
env:
SITE_URL: ${{ vars.SITE_URL }}
GITHUB_SHA: ${{ gitea.sha }}
run: |
sleep 2
live=$(curl -fsS "$SITE_URL/VERSION")
case "$live" in
"${GITHUB_SHA:0:12}"*) echo "live site is at $live" ;;
*) echo "live site reports '$live', expected ${GITHUB_SHA:0:12}" >&2; exit 1 ;;
esac
+16
View File
@@ -0,0 +1,16 @@
site/
node_modules/
.DS_Store
dist/
patches/
# pixi environments
.pixi/*
!.pixi/config.toml
# Python
__pycache__/
*.pyc
# the Quarto example site's output and Quarto's own state
quarto/_site/
quarto/.quarto/
quarto/_extensions/pplus/engine/
+58
View File
@@ -0,0 +1,58 @@
# AGENTS.md
Instructions for coding agents (and people) changing Programming+. Read this first, then the [README](README.md) for what the app is and where things are. When this file and a task's instructions disagree, the task wins; say so in your summary.
## Build, test, and the gate
```bash
pixi run test # build, then every test (node --test against dist/, the corpus pipeline's Python tests included)
pixi run ci # the gate: every test, and no Mojo program of ours failing
```
Without pixi (a sandbox with only Node and Python):
```bash
tsc -p tsconfig.json && node --test tests/*.test.mjs
python3 scripts/mojo/corpus.py status --strict
```
**Finish every change with the gate green.** The baseline passes completely; there is no known failure to work around. If a test fails, fix the cause or stop and report it. Do not skip, loosen, or delete a test to get green.
The full suite takes about two minutes. While iterating, build and run one file: `tsc -p tsconfig.json && node --test tests/state.test.mjs`.
## Hard rules
1. **Do not edit generated files by hand.** `src/mojo/generated/*` and `quarto/_extensions/pplus/syntax/mojo.xml` come from the corpus pipeline (`pixi run mojo-emit`, `mojo-status`, `play`). `quarto/_extensions/pplus/pplus-views.css` comes from `styles.css`, and `pplus-hw.css` and `course/*.css` beside it from `styles/course/` (`pixi run quarto-css`; a test fails while they are out of date, so run it after changing a rule the views use). `mojo/corpus/` comes from `mojo-harvest`. `mojo/golden/` holds godbolt's answers and comes only from `mojo-verify`.
2. **Do not edit a `.mojo` file's text unless the task needs it.** A stored godbolt answer is keyed by the whole source, header comments included, so any edit (even to a comment) makes the program unverified until it is asked again on the network. If you add or change one, say in your summary that it needs `pixi run mojo-verify-item '<corpus>/<name>'`.
3. **Never claim Mojo compiles, runs, or prints something without the real compiler's answer.** Mojo is pinned to 1.1.0. The checker may never report an error on a program the compiler accepts, and the interpreter must print exactly what godbolt printed or decline; `tests/mojo-check.test.mjs` and `tests/mojo-run.test.mjs` hold them to that. Every Mojo construct you write into the app must pass `checkMojo`, and every standard-library name must exist in `src/mojo/generated/stdlib.ts` or `types.ts`.
4. **No new dependencies.** TypeScript is the only npm package. There is no bundler, no framework, and no runtime dependency; the corpus pipeline is Python's standard library only. CodeMirror is vendored as one built module (`src/vendor/`), rebuilt only by `scripts/vendor/codemirror.sh`.
5. **You have no network** in most sandboxes. Godbolt (`mojo-verify`, Compile & run) and GitHub (`mojo-harvest`, `mojo-fetch`) need one. Never fake their results; leave those steps to the owner and list them.
6. **Keep the workspace working while you change it.** Code panes are always the CodeMirror editor (`Editor` in `src/ui/editor.ts`, over the vendored `src/vendor/codemirror.js`), never a `<textarea>`; `tests/editor.test.mjs` checks it. Keep the workspace's parts as they are unless the task changes them: the pane tabs over one editor, the stepper docked under the editor, the side column (the inspect panel, whose first tab is the Run view), and the dock; in the Hardware area, the code on the left and the arrangeable board on the right. Restyle or rearrange them only when asked, and after any UI change open the app (`pixi run dev`) and check that the editor has line numbers and highlighting, the stepper steps, and the styles loaded.
## Conventions
- **Commands are pixi tasks.** Name them as `pixi run <task>` in docs, comments, and messages. A new command is a task in `pixi.toml` with a `description` and a row in the README's Commands table; `tests/tasks.test.mjs` fails otherwise, and also fails on any `pixi run <name>` that names no task. `package.json` keeps only `build`, `watch`, `check`, `dev`, `test` (what CI uses).
- **Docs.** The README is the front door: keep it short. Put behavior in [docs/app.md](docs/app.md), exercises in [docs/exercises.md](docs/exercises.md), Mojo of our own and the pipeline in [docs/mojo-corpus.md](docs/mojo-corpus.md), the engines in [docs/engines.md](docs/engines.md), deployment in [docs/deploy.md](docs/deploy.md), and the Quarto extension in [quarto/README.md](quarto/README.md). Update the document a change belongs in, in the same commit.
- **Tests run against `dist/` with no DOM.** Put logic in DOM-free modules (`src/core/`, `src/services/`, `src/mojo/`, `src/quarto/`) and test it there. The views in `src/ui/views/` also run outside a browser, under the small document of `src/quarto/dom.ts`, when the Quarto extension renders them: a view may use the selectors that document knows (compound selectors and the descendant combinator) and must not need layout to produce its markup. When a test needs `localStorage`, install a fake on `globalThis` and remove it in `finally`, as `tests/state.test.mjs` does. For a UI change, write a short manual check list in the commit message.
- **TypeScript.** Strict mode, ES modules, imports with the `.js` suffix (`from './state.js'`). Indent like the file you are editing (some files use two spaces, some four).
- **Stable ids.** Diagnostic ids (`matho-refused`, `reserved-name`, ...) and reference section ids are asserted by tests and linked from guides. Change one only on purpose, and update every test and link that names it.
- **Saved state.** `PlayState` in `src/core/state.ts` is what share links, `localStorage`, and `.pplus.json` files hold, and `normalize()` reads it. A new field goes into `normalize()`; a field the student edits goes into `EDITS` (it drives `editedFrom()` and `editsFingerprint()`).
- **Writing.** User-facing copy is US English (color, behavior, optimized, labeled). Plain sentences; say what a thing does, not how good it is.
## Adding things
| To add | Do |
|---|---|
| A catalog problem | `pixi run new-exercise <id>` for one built around a Mojo program, or copy `src/exercises/_template.ts` ([docs/exercises.md](docs/exercises.md)) |
| A question about the compiler | `pixi run new-probe <name> "<question>"` |
| Realistic Mojo for the interpreter | `pixi run new-stress <name> "<what it exercises>"`, with the output you predict in `# expect-stdout:` lines |
| A pseudo regression program | a file in `tests/corpus/` whose `// EXPECT:` lines are the output it must print |
| A command | a task in `pixi.toml` and a row in the README's Commands table |
| A language | a `LanguageService` (`src/core/types.ts`) in `src/services/`, registered in `src/services/index.ts` |
| A Quarto shortcode | a function in the table `quarto/_extensions/pplus/pplus.lua` returns, a row in `SHORTCODES` (`src/quarto/shortcodes.ts`) and in `scripts/check-pages.mjs`, a sample in the gallery (`src/ui/quarto.ts`) and a use in `quarto/example/`; a rendered view is a case of `renderStatic` (`src/quarto/render.ts`); a view of the machine is a name in `HW_NAMES` (`src/quarto/machine.ts`), `HW_VIEWS` in `pplus.lua` and `HW_VIEWS` in `scripts/check-pages.mjs` |
## Delivering work
- One logical change per commit, with a message that says what changed and why: the problem first, then what each part of the change does.
- When the owner asks for patches, export them with `git format-patch -o patches/ <base>` (the `patches/` folder is ignored by git) and do not paste whole files into chat. If the tree you were given has no `.git`, run `git init` and commit it unchanged first, so the patches have a base.
- End with a summary: what you changed, the gate's result, anything you could not verify (network steps, manual UI checks), and anything you noticed but left alone.
+117
View File
@@ -0,0 +1,117 @@
# Programming+
Programming+ takes a procedure **from an idea to Mojo to the machine**, built for a world where writing code is easy and knowing what it does is the job. It has three areas (`src/core/areas.ts`):
- **Bridge**: write the procedure as plain-English steps (**lingo**), equations written in LaTeX (**matho**), the notation that can completely specify any procedure (**pseudo**), or a specification you prove against (**speco**); the others follow as you type, and Mojo is generated from the pseudo, always labeled as generated.
- **Developer**: Mojo only. The checker's advice as you type, every step and every value in one Run view, a fuzzer that lists what it tried, and the real Mojo compiler's verdict.
- **Hardware**: the code beside a board you arrange: registers, memory, the stack, cache lines, the caches, virtual memory, the pipeline and the out-of-order core, with Mojo and its x86-64 as tabs, linked line by line.
A catalog of worked problems comes with it, each opening in every area it has something to show in, and any view can be shared as a link or embedded in a page. With Quarto, a page can also run a program kept beside it while the page renders, and show the run, a stepper, the flowchart, the proof and the rest without an iframe, down to the machine itself (registers, caches, the pipeline, the core, stepped). The **With Quarto** page (`#/quarto`) is a gallery of every shortcode.
It is a static single-page app: TypeScript compiled by `tsc`, no bundler, no framework, no runtime dependencies. Everything it says about Mojo is pinned to **Mojo 1.1.0** and checked against the real compiler on [Compiler Explorer](https://godbolt.org).
## Quick start
With [pixi](https://pixi.sh) (it brings the pinned Mojo, Node and Python):
```bash
pixi run dev # build, then serve on http://localhost:4173
pixi run test # build, then every test
```
Without pixi, with Node 20 or later (and `python3` for the corpus pipeline's tests):
```bash
npm install && npm test
npm run dev
```
## Commands
Every command is a pixi task (`pixi task list` shows them with their descriptions). `tests/tasks.test.mjs` fails if this table and `pixi.toml` disagree.
| Task | What it does |
|---|---|
| **Build and test the app** | |
| `install` | Install TypeScript, the only npm dependency |
| `build` | Compile `src/` to `dist/` |
| `watch` | Rebuild `dist/` on every change |
| `check` | Type-check only |
| `dev` | Build, then serve on http://localhost:4173 |
| `test` | Build, then run every test, the corpus pipeline's Python tests included |
| `check-pages <dir>` | Run every program embedded in the Quarto pages under a folder ([quarto/README.md](quarto/README.md)) |
| `engines-diff <static>` | Compare the vendored course code with a course checkout ([docs/engines.md](docs/engines.md)) |
| **Write content** | |
| `new-exercise <id>` | Start an exercise whose Mojo lives in `mojo/local/<id>.mojo` ([docs/exercises.md](docs/exercises.md)) |
| `new-probe <name> <question>` | Start `mojo/probes/<name>.mojo`: one question about the compiler ([docs/mojo-corpus.md](docs/mojo-corpus.md)) |
| `new-stress <name> <about>` | Start `mojo/stress/<name>.mojo`: realistic Mojo that tests the interpreter |
| `play <name>` | For `mojo/local/<name>.mojo`: run, verify on godbolt, build, list the assembly, test |
| `play-watch <name>` | The same, again on every save (tests off) |
| `quarto-export <name> <dir>` | Copy a `mojo/local/` program, its x86-64 and setup beside a Quarto page, and print the shortcode |
| `quarto-css` | Regenerate the extension's `pplus-views.css` from `styles.css` (a test fails while it is out of date) |
| `quarto-engine <dir>` | Copy a built Programming+ into a site's `_extensions/pplus/engine`, for the rendered views ([quarto/README.md](quarto/README.md)) |
| `quarto-example` | Render the example site in `quarto/example`, every shortcode on real pages (needs Quarto) |
| **The Mojo corpus** ([docs/mojo-corpus.md](docs/mojo-corpus.md)) | |
| `mojo-verify` | Ask godbolt about every program with no answer yet (network) |
| `mojo-verify-item <id>` | Ask again about one item, e.g. `'probes/life-*'` (network) |
| `mojo-verify-dry` | Show what `mojo-verify` would send; send nothing |
| `mojo-verify-diagnostics` | Also check the compiler's own diagnostic tests (opt-in; network) |
| `mojo-status` | Judge every item from the stored answers, offline; writes `mojo/golden/STATUS.md` |
| `mojo-status-strict` | The same, and fail if a program we wrote fails |
| `mojo-harvest` | After editing `mojo/pin.json`: fetch Modular's sources, process, regenerate (network) |
| `mojo-harvest-local [dir]` | Harvest, with zips standing in for sources the pin leaves unresolved |
| `mojo-harvest-offline [dir]` | Harvest from zips only, no network |
| `mojo-fetch` | Re-resolve every ref in the pin and rewrite the lock (network) |
| `mojo-emit` | Regenerate `src/mojo/generated/` from the pin and corpus, offline |
| `mojo-test` | The corpus pipeline's own tests |
| `mojo-run <file>` | Run one Mojo file on the pinned local compiler |
| `mojo-probes-local` | Run every probe on the local compiler (a quick look) |
| `mojo-update` | After editing the pin: harvest, verify, status, test |
| **Ship** ([docs/deploy.md](docs/deploy.md)) | |
| `ci` | What CI runs: every test, and no program of ours failing |
| `site` | Test, then assemble `site/` |
| `deploy [slug] [target]` | Publish `site/` to `/srv/www/<slug>`, optionally over SSH |
## Where things are
```
AGENTS.md rules for changing the code (read first)
index.html, styles.css the page and the app's stylesheet
src/
main.ts the hash router
core/ state and its URL codec, the session, the catalog, the areas, the language reference
sync/ the translators between the languages and the hub that keeps the Bridge's panes in step
services/ one adapter per language behind LanguageService (lingo, matho, pseudo, speco, mojo, asm), godbolt.ts
mojo/ the Mojo checker, interpreter, lifetimes, and AT&T-to-Intel listing translator
mojo/generated/ generated from mojo/pin.json and the corpus; do not edit
ui/ the shell (one per area), the home page, the "With Quarto" gallery, the editor, the embeds, the views
quarto/ the Quarto extension's rendered views: a program run and drawn by the views, as HTML (render.ts),
the small document they draw into outside a browser (dom.ts), the shortcode list (shortcodes.ts)
ui/hw/ the Hardware area's machine board, over the course's x86-64 views
exercises/ one file per catalog problem
curriculum/ a lesson corpus kept as an interpreter fixture (tests/curriculum.test.mjs); no UI
engines/ the course site's language engines (docs/engines.md); do not edit here
vendor/ CodeMirror 6 as one built module; scripts/vendor/ rebuilds it
styles/course/ the course site's widget stylesheets, copied unchanged (and bridge.css, ours)
tests/ node --test against dist/; tests/corpus/ holds pseudo regression programs
mojo/ the Mojo corpus: the pin and lock, harvested material, our probes, local and
stress programs, and godbolt's answers (golden/)
scripts/ the tasks above; scripts/mojo/ is the corpus pipeline (Python, standard library only)
quarto/ the Quarto extension (_extensions/pplus) and an example site using every shortcode (example/)
docs/ the documents below, and the Caddy site block
scratch/ ignored by git: a place for experiments
```
## Read next
| Document | For |
|---|---|
| [AGENTS.md](AGENTS.md) | Rules for anyone changing the code, coding agents included: the gate, what not to edit, conventions |
| [docs/app.md](docs/app.md) | What the app does: the three areas, translation between languages, its links, and how embeds behave |
| [docs/sync-coverage.md](docs/sync-coverage.md) | What each translator can say, written by the tests: which programs translate fully, and why the rest do not |
| [docs/exercises.md](docs/exercises.md) | Adding a catalog problem |
| [docs/mojo-corpus.md](docs/mojo-corpus.md) | Writing Mojo of our own (probes, exercise programs, stress programs) and moving to a new Mojo version |
| [docs/asm-coverage.md](docs/asm-coverage.md) | Which instructions compiled Mojo uses, against what the machine models |
| [docs/engines.md](docs/engines.md) | The vendored course engines and stylesheets, and how they differ from the course |
| [docs/deploy.md](docs/deploy.md) | Building the site and publishing it to the droplet |
| [quarto/README.md](quarto/README.md) | Embedding views in a Quarto site |
+28
View File
@@ -0,0 +1,28 @@
# The site block for one slug under /srv/www. Caddy issues and renews the
# certificate itself, so this is the whole configuration for the host.
#
# /srv/www/pplus is a symlink to the current release (scripts/deploy.sh);
# Caddy follows symlinks by default. Routing lives in the URL hash, so every
# path is the one page and no rewrite is needed beyond serving index.html.
pplus.scient.ing {
root * /srv/www/pplus
encode zstd gzip
file_server
# The modules and the stylesheet change on every deploy: revalidate rather
# than serve a stale module against a new index.html.
@code path *.js *.css
header @code Cache-Control "no-cache"
header /VERSION Cache-Control "no-store"
# Course pages embed views in iframes, so no X-Frame-Options here; allow
# framing from the course origins, and from a local `quarto preview` of them.
header Content-Security-Policy "frame-ancestors 'self' https://scient.ing https://*.scient.ing http://localhost:* http://127.0.0.1:*"
# A deleted path falls through to the app rather than a bare 404.
handle_errors {
@notfound expression {http.error.status_code} == 404
rewrite @notfound /index.html
file_server
}
}
+223
View File
@@ -0,0 +1,223 @@
# What the app does
This is the reference for the app itself: the three areas, their links and embeds, and what each part of the workspace does. For commands, see the [README](../README.md).
## The areas
The app has three areas, one workspace layout each (`src/core/areas.ts`, the `AREAS` table; the names are placeholders the owner can change in one line). A problem is one saved state shared by all three, so moving from one area to another carries the work along. The area comes from the route, not the state. Each area is its own page, reached from the nav and the home page; the toolbar names the area you are in and offers a switch only to an area that would show the open pane exactly as it is (`safeSwitches` in `src/core/areas.ts`): in practice Developer and Hardware on the same Mojo, and the Bridge's Mojo tab once the student's Mojo is its translation. A learner moving between areas therefore never finds the work changed by the move itself; **Edit in Developer** and **Open in Hardware** are the deliberate moves that carry work across.
| Area | For | Panes | Inspect tabs | Dock |
|---|---|---|---|---|
| **Bridge** (`bridge`) | taking a written problem or idea into Mojo | lingo, matho, pseudo, speco, Mojo | run, flowchart, data flow, prove, tests | setup, output, problems, compiler |
| **Developer** (`dev`) | Mojo coding | Mojo | run, flowchart, data flow, tests | setup, output, problems, compiler |
| **Hardware** (`hw`) | Mojo and x86-64 with the machine in view | Mojo, x86-64 | none: two panes, the code and the board, whose cards hold the run, registers, memory, caches, pipeline, chip, setup, output, problems and compiler | none |
Each catalog problem names the area it opens in (`area` on the exercise): Hardware for `asm-*` problems, Developer for ones that are only a Mojo program, Bridge for the rest. The panes a state is shown with come from the area, so a link made in one area opens in another on that area's first choice of pane. Layout (the dividers, the dock tab, what is folded) is kept per area (`layout: { bridge, dev, hw }` in the state). **Open in Hardware** on the compiler's listing puts a function into the x86-64 pane and switches area.
### The home page
The home page (`src/ui/home.ts`) opens with why the platform exists: work is done by human and artificial agents, producing code and analyses is cheap, and someone still has to take responsibility for the output, which takes knowing what it does step by step (the hero's sign-off panel lists who might have made it above the sentence that has to be signed). Three columns follow (producing got cheap, ownership did not, the gap from novice to expert is where tools are missing), with AlphaFold as the example. Then each area gets a card with its name and tagline from `AREAS` and a sample the engines make on the spot, each in a window of the same height: the Bridge turns the mean, written as an equation, into pseudo, lingo and labeled Mojo through the same hub the panes use; Developer shows the checker's advice on a moved-out value and the first steps of `count_base`; Hardware shows the registers and the cache line of the first load in `asm-two-pointers` on the teaching machine. **Why Mojo** says why it is the one real language: it reads plainly, it is compiled with strict rules there is always a precise answer to, it spans a first program to hand-written GPU kernels, and we believe it will lead in the computational sciences. The notations section shows `count_base` in six even boxes, except matho, which cannot express it (B is a character) and says so. The problem list shows the areas each problem opens in (`areasFor` in `src/core/areas.ts`: its own area first, then the Bridge if it has lingo, matho, pseudo or speco, Developer if it has Mojo, Hardware if it has x86-64), with a link to each, and filters by area.
### The Bridge workspace
Four languages are kept in step (see [Translation between languages](#translation-between-languages)): tabs run **lingo, matho, pseudo, speco**, then **Mojo (from pseudo)** set slightly apart.
- **Link state on every tab.** ✎ the pane you are editing (the others follow it), ⇄ in step, ⚠ not in step (the reason is in the tooltip and in the banner above the editor), nothing for a pane still **as authored** (nothing has been translated yet; the first edit makes that pane the authority).
- **Typing never fights the cursor.** The pane being edited is never rewritten. The other panes are brought up to date when their tab is shown, replacing only the part of the text that changed, so the cursor and scroll position of a pane stay put. Each such update is its own undo step (the editor's `setSynced`, a `sync` user event that history does not join to typing), so Ctrl+Z in a pane steps back to what it showed before the sync, and, as with any change to a pane, that pane then becomes the authority. Loading a problem is not an undoable edit.
- **A pane that is not in step** (matho for a `WHILE`; anything while the pane you edited does not read) keeps its last text, is read-only, and says why, with an **Edit anyway** button that makes it the authority. The stepper does not step a stale lingo or matho pane; it steps the pseudo.
- **Mojo (from pseudo)** is read-only, labeled *Generated from pseudo*, and computed from the pseudo on the fly (`Session.derivedMojo()`; the state's own `sources.mojo` is untouched). It steps in the Mojo interpreter, is checked, and **Compile & run** sends it to the real compiler. **Edit in Developer** copies it into the Developer area's Mojo pane (asking first if that pane holds something else) and records `mojoOrigin: 'generated'`; the first edit there makes it `'generated-edited'`, and the Mojo pane says so.
- **Prove and Tests** work on the hub's pseudo with the speco woven in, whichever pane you edited.
Every area is an IDE-style workspace: the language panes as tabs over one editor; under it the stepper and what runs next; beside it an inspect panel (the Run view, flowchart, data flow, proof, tests) whose tabs appear only when they apply to the pane; under everything a dock for the output, the problems, the real compiler's answer, and the machine model's numbers. A catalog of worked problems comes with it.
### The Hardware area
Two panes, and nothing shown twice. On the left the code (the Mojo and x86-64 tabs over one editor) and the stepper under it. On the right the **board** (`src/ui/hw/board.ts`), a set of cards in a two-column grid (twelve tracks, a half card spanning six): the course's own x86-64 views (`src/engines/asm86/views.js` and `hwviews.js`, the widgets the course pages use, with the course's stylesheets from `styles/course/`), mounted over the x86-64 pane's run and moved by the stepper, and the app's own views as cards too: Setup, Output, Problems, the Compiler, the Run view (for the Mojo pane), the counters, and the cache lines. The area has no inspect panel and no dock (`workspace: 'board'` in `AREAS`); Compile & run and a click on a diagnostic bring their card into view, adding it if the board does not show it.
**Arranging it.** Presets along the top set out cards that make sense to see at once. **+ Add a view** opens every card by group (Program, Registers and memory, Memory system, Time, The chip); click one to put it on the board or take it off. Drag a card by its title to move it (or use ↑ ↓), ↔ widens it to the whole row or narrows it to share one, × takes it off. The arrangement is kept per area (`layout.hw.board`, a list of `{ id, wide? }`, cleaned by `normalizeBoard`), and the preset buttons show which preset it is, if any. Every change is a pure function in `src/core/hardware.ts` (`moveItem`, `addItem`, `removeItem`, `toggleWide`, `presetOf`).
The presets:
- **Registers and memory**: a card per register the program touches (amber when the last instruction wrote it, with the value before), with every narrower name (`eax`, `ax`, `al`, `ah`) for the registers the program also uses at a narrower width; the flags, with the ones the last instruction read; the effective address as base + index × scale + displacement; the memory regions byte by byte with the load (blue) or store (purple) highlighted; and the stack as eight-byte slots with `rsp` and `rbp` marked.
- **Caches**: memory below the instruction set. **Cache lines** (the board's own view, `src/ui/hw/lines.ts`) shows, for each load and store of the last instruction, the whole line it touched as a row of bytes: the bytes this access used, the ones the program used before, the ones it uses later, and the ones it never uses, with where the line was found (an L1d hit, or the level it came from) and "used 8 of this line's 64 bytes". Beside it the course's L1d cache as sets and ways (hit green, miss red, the evicted line named), the hierarchy with the path each access took and running totals, and, with virtual memory on, the page walk and the TLB.
- **Pipeline**: time. The classic five-stage pipeline cycle by cycle (stalls amber, wrong-path fetches red, the whole run's lost cycles by cause), the micro-ops the last instruction became and the ports each can run on, what bounds the whole run (the dependency chain, the busiest ports, the front end), and the out-of-order timeline of when each instruction entered, ran and retired.
- **Whole chip**: the core from branch predictor to memory with the parts the last instruction used lit up, each lit edge with an arrowhead on the end its data reached (a load's data back up from wherever it was found to the load port, a fetch that missed back into L1i, a store out through the store buffer, the result into the registers from the port that produced it); the listing with each instruction's address and bytes beside the last instruction's machine code broken into prefix, REX, opcode, ModRM, SIB, displacement and immediate; and last, inside the out-of-order core (reorder buffer, ports, rename table, with its own cycle buttons), whose table grows and shrinks with what is in flight.
**The listing and the encoding as a pair.** When the two are next to each other at half width, `board.ts` marks them as a pair: on a board at least 960px wide they share a row two to one, and on a narrower one the encoding sits under the listing. The listing then scrolls in its own box, as tall as the encoding (300px when stacked), and keeps the instruction about to run in view; only that box scrolls, never the page.
**Nothing moves while stepping.** A card never gets shorter while one run is stepped: each keeps the tallest height it has reached as its minimum. When the board is built it first draws a spread of the run's steps (all of a short run, forty of a long one, always the last) before the browser paints, so views that grow with the run (the pipeline, the timeline) start at their final size. The minimums start over with a new run, machine or arrangement, and when the board's width changes. The same rule holds the Run view's panel of followed variables, and a string or list with no value yet keeps the height of its ruler. Elsewhere the boxes that change with each step have fixed sizes: what runs next (two lines, each cut with an ellipsis, the whole text in its tooltip), the loop status (one line), the register cards' "was" line, and in `styles/course/bridge.css` the core's caption, the address arithmetic and the cache-line list.
- **Mojo and the compiler**: the Run view of the Mojo pane, the real compiler's answer and listing (with Open in Hardware), the output and the problems.
- **Counters** (a card in any arrangement): the run as totals in the style of `perf stat`, and for code sent from the Compiler view what each Mojo line cost.
**Mojo and x86-64.** The two are tabs over the one editor, never split side by side. x86-64 sent from the Compiler view ends each instruction with `; mojo line N`, godbolt's own line table (`forSimulator` in `src/mojo/att.ts`); through it, clicking a line in either pane marks the matching lines in the other tab, lit when that tab is selected (`asmMojoLines` and `relateAsmMojo` in `src/core/hardware.ts`). A short note in the pane head says so; for x86-64 written by hand, which has no such table, it says the lines are not linked. The Mojo there carries its generated label and godbolt badge, as everywhere. Compiling needs the network; without a listing the area works on hand-written x86-64 alone.
The board's **machine** switch (also in the Setup card): `teaching` (caches small enough that misses happen on small data), `realistic` (shaped like a desktop core: 64-byte lines, an L3, a next-line prefetcher), or `ideal`; and **virtual memory** turns on paging with a TLB. The state stores it as one string (`machine: 'teaching+paging'`; `parseMachine` and `machineSpec` in `src/core/hardware.ts`), and the run hands it to the hardware model through the trace, so the board's views and the counters always describe the same machine. With virtual memory on, a line is the physical one and the access keeps the address the program wrote.
What each card mounts, with what options, and the frame each view draws at each step are decided DOM-free in `src/core/hardware.ts` and tested for every problem with assembly (`tests/hardware.test.mjs`); a view that throws says so in its own card and leaves the rest working. The course files draw dark on `body.quarto-dark`, so the app keeps exactly one of `quarto-light` and `quarto-dark` on `<body>`, matching the theme it shows (`src/ui/theme.ts`).
### Mojo badges
Two independent badges sit beside any Mojo the site shows (pane head, Compiler view, Mojo embeds, Share dialog):
- **Generated from pseudo** (or **Started from generated Mojo** once edited). `mojoProvenance` (`src/core/provenance.ts`) answers for every view: the Bridge's Mojo is always generated, elsewhere `PlayState.mojoOrigin` says. Generated Mojo starts with a header comment, so copying it keeps the warning. It never shows beside "verified on Mojo" (which is only for an exercise's own program). Only the Developer area's **I've reviewed this** button clears it (`Session.clearMojoOrigin`), taking the header comment off too; compiling and editing do not.
- **Compiled on godbolt**, with the outcome (ran, exit N / did not compile / timed out), the compiler and build level in the tooltip, or **Edited since compile**. It is keyed by a hash of source, input and build level (`compiledStatus` in `src/core/compiles.ts`), so a one-character edit, another level or another input removes it. Full answers are the newest 16 in `pplus.compiles`; a summary index (`pplus.compiled`, up to 300) lets the badge outlive them. Neither is in `PlayState`, a share link or a file: a link never claims a compile that this browser did not make. The badge means the compiler answered, not that the program is right.
### Best practices (the helper)
`src/mojo/practices.ts` (DOM-free) turns the gap between the translator's literal Mojo and the Mojo a person would write into things to learn from. It is **off by default in both the Bridge and the Developer area**: each area has its own switch (the toolbar's "Best practices" button), remembered in this browser (`pplus.practices.bridge`, `pplus.practices.dev`; `src/core/prefs.ts`), never in `PlayState` or a link. While a switch is off the rules never run (a spy test holds it to that) and nothing about them is shown. The translator never imports the helper, so the Bridge's Mojo is the same literal translation either way (a grep gate and a snapshot test keep it so).
A rule is `{ id, title, why, docUrl, example, apis, detect }`. The starting rules: declare-then-assign → `var n = …`; `x = x + 1` → `x += 1`; an index loop that only reads codepoints → `for cp in t.codepoint_slices()`; `raises` on a function that cannot raise; a never-changed number that sizes a loop → `comptime`; argument conventions (`imm` written out is the default; `mut` on an argument never changed); `reserve` before a loop that appends a known number of times; `name^` for a last use handed to a `var` argument; `.copy()` for a list copy that says so. (The plan said `read`; Mojo 1.1.0 renamed it `imm`, so the helper says `imm`.)
- **Bridge:** the Best practices dock tab lists each finding with the Mojo line, the pseudo line it came from (the hub's line map), the reason, before and after, the manual link, and, where true, how to write the pseudo so the translator writes the better form. Clicking one lights both lines. The Mojo is read-only, so rewrites are shown, not applied. **Show idiomatic version** (in the Mojo tab, off until chosen) shows a copy with the safe rewrites applied, only if it passes the checker no worse than the literal one and the interpreter prints exactly what the literal one prints; it keeps the generated label ("Generated from pseudo, with N best-practice rewrites").
- **Developer:** findings are `note` diagnostics with origin "best practices" (never an error or a warning, so they never look like the compiler) in Problems and the gutter, each with a one-click fix where the rewrite is safe. A rule that cannot promise a safe rewrite (`comptime`) explains and leaves the editing to the student.
- **Tests** (`tests/practices.test.mjs`): every rule's example passes the checker, runs, and prints the same before and after, and the rule's fix turns one into the other; every method a rewrite names is in the harvested index; a false-positive gate runs the rules over Modular's own tested programs in `mojo/corpus/manual/` against a reviewed allowlist; each exercise's findings are pinned by a snapshot; applying every fix to each exercise's generated Mojo and each `mojo/local/` program keeps it checking and printing the same.
### Saved versions
A student can save the state of their work under a name and come back to any saved version from the **Versions** menu in every area's toolbar (`src/core/versions.ts`, DOM-free, storage injectable).
- **What a version holds:** every source, the link bookkeeping (`sync`), where the Mojo came from (`mojoOrigin`), the call, the input, the assembly setup and machine, and the build level, plus the area it was saved in, a name, and a time. Not the layout, the step, or the open tab: restoring a version changes the work and never where you are looking. (`EDITS`, which decides whether work differs from the problem as written, keeps leaving `sync` out; the version fingerprint adds it, so restoring brings the links back as they were.)
- **Where they live:** `localStorage`, one list per piece of work: `pplus.versions.<problemId>`, or `pplus.versions.ws.<workspaceId>` for work that began from a share link or a file (`PlayState.workspace` is added when such work is first saved, and the address is updated so a reload finds it). Every area shows the same list. At most 50 per list: when it is full the oldest automatic version makes room, and if only named ones are left the save is refused rather than delete one. The menu says when the browser's storage is nearly full.
- **Never losing work:** choosing a version, **Reset**, and **See the new version** first save work that no version holds as "Before switching (time)" or "Before reset (time)". If that save is refused, the switch does not happen.
- **A problem that changed under saved edits** shows a banner with **See the new version**: your edits become the version "My edits, before the problem changed" and the problem opens as it is now.
- **Between browsers:** Share → Download writes the state and, with a checkbox (on by default), its versions; Open… puts them in the right list and never overwrites a version that has the same id. A share link carries only the current state.
### With Quarto
`#/quarto` (`src/ui/quarto.ts`, linked from the nav, the footer, and a section of the home page that shows one shortcode beside the stepper it makes) is a gallery of the Quarto extension's shortcodes ([quarto/README.md](../quarto/README.md)). Each card shows what an author writes (the shortcode, and every program file it names, in tabs) and what the reader gets, drawn when the card scrolls into view by the same code `quarto render` runs: `renderStatic` for the rendered views and the machine, this app's own `#/embed/...` route in an iframe for the live ones. The cards can be filtered by kind (rendered with the page, the machine, live, text); one machine card has a menu of every `pplus-hw-<view>` and draws the one chosen. `#/quarto#<shortcode>` scrolls to a card, `#/quarto#setup` to the set-up steps. The page loads the extension's `pplus.css` and `pplus.js` from the site (`scripts/assemble.sh` copies the extension into `site/`), so the steppers and "make it live" behave exactly as on a Quarto page. The shortcodes, their options and the sample programs come from `src/quarto/shortcodes.ts` and `galleryFiles()`; `tests/quarto-gallery.test.mjs` renders every sample and holds each program in it to its header lines.
## Links
| URL | Opens |
|---|---|
| `/#/` | the home page: pitch, problems, reference |
| `/#/<area>/p/<problem>` | a catalog problem in an area (`bridge`, `dev` or `hw`), with the student's saved edits (localStorage) |
| `/#/<area>/s/<state>` | a shared state in an area: every pane, the call, the setup, the step — compressed into the link |
| `/#/embed/<view>/<state>` | one view, no chrome, for an `<iframe>` |
| `/#/embed/<view>/p/<problem>` | one view of a catalog problem |
| `/#/quarto` | With Quarto: the gallery of the Quarto extension's shortcodes (`#/quarto#<section>` scrolls to one) |
Nothing else is a route: `#/p/<problem>`, `#/s/<state>` and the other earlier forms open the home page. `<view>` is `playground` (the whole workspace; `?area=dev` picks the area, Bridge by default or the problem's own), `trace`, `table`, `flow`, `data`, `life`, `proof`, `tests`, `problems`, `compiler`, `asm` (the machine numbers), or a pane name (`lingo`, `pseudo`, `speco`, `mojo`, `asm`) to show just that editor with its problems under it. Query parameters on an embed: `?t=12` parks the stepper, `?ro=1` makes the editor read-only; `area`, `panel`, `lang`, `build`, `machine`, `dock`, `docktab`, `editor`, `side`, `dockheight` and `theme` arrange the example as the playground's controls do (`applyEmbedParams` in `src/core/state.ts`).
A reader's edits in an embed are saved in their browser, in that embed's own save (one per embedded example, shared by pages that embed the same one), never in the app's save for the problem. Once they have changed something, **Reset** appears beside "open in Programming+" and puts the author's version back. An embed keeps a save only while it holds edits, so a reader who has not changed an example always sees the author's current version. A read-only embed (`?ro=1`) saves nothing.
The **Share** button in the app produces the app link, a ready-to-paste `<iframe>` for any view, and the Quarto shortcode for the same state (`{{< pplus-playground state=… >}}` or `{{< pplus-embed state=… view=… >}}`). Without the extension, in a Quarto page:
```html
<iframe src="https://pplus.scient.ing/#/embed/trace/p/match?t=12"
width="100%" height="520" style="border:1px solid #ccc;border-radius:8px"
loading="lazy" title="Programming+: find a pattern, stepped through"></iframe>
```
## The workspace
- **Step through**, with the tools a tutor would use at a whiteboard: the next line is called out before it runs with what it reads and writes; strings and lists draw as rulers with the position being read highlighted; every variable shows its previous value and a link to the step that changed it; click a line number for a breakpoint and run to it; jump by loop pass; **predict mode** asks what the next step will write before you take it and keeps score; play at any speed; export the trace as CSV. Keyboard: → ← Shift+→ Home End Space B P, and ? in the toolbar lists them.
- **Light and dark**: the ☾/☀ button; follows the system until you choose. Embeds take `?theme=dark`.
- **Table of values**: the table a student draws by hand, drawn by the machine: a column per step that changed something, a row per name, the new value in the cell, blank for unchanged; click a step to jump the stepper there; copy as text.
- **Flowchart**: laid out from the structure of the pseudo (so loops loop and branches branch), each box shaded by how often its line ran in the last run, each loop labeled with its passes, each arrow out of a decision with how often it was taken; a box that never ran is dashed. Click a box to reveal its line; download as SVG.
- **Data flow**: inputs on the left, `RETURN` and `OUTPUT` on the right, one arrow per assignment that reads the one and writes the other, labeled with its line, dashed when a condition only decides whether it happens.
- **matho pane**: equations as a source language, written in LaTeX (`src/services/matho.ts`). One `FUNCTION` per equation; `\sum` and `\prod` become accumulator loops, subscripts become positions (with the 1-based shift when the sum starts at 1), `\begin{cases}` becomes `IF`/`ELSEIF`, Greek letters become names, references to earlier equations become calls hoisted out of loops when their arguments do not change. Every decision is a note on the equation's line; integrals, infinity, limits and derivatives are refused with the finite procedure to write instead. The trace steps the pseudo with the marker on the equation each step came from.
- **Numerics**: `SUM_OF MEAN_OF VARIANCE_OF STDEV_OF MEDIAN_OF DOT NORM_OF FILL CHOOSE RANDN FLOOR CEIL LOG10 SIN COS TAN ATAN2 PI()`, and `PARALLEL FOR`, a loop whose passes may run at once, checked at run time: two passes touching one location stop the run with a data race that names the location and the passes.
- **Mojo for every exercise with pseudo**: each has its Mojo in `mojo/local/`, so the Developer and Hardware areas always have something to show for it; `tests/mojo.test.mjs` runs each Mojo program in the interpreter and checks it prints what the exercise expects.
- **Panes**: the area's own (see the table above), dimmed when empty (a dimmed tab opens an empty pane to write in), as tabs over one editor (CodeMirror: search and replace with Ctrl+F, go to line with Ctrl+G, bracket matching, undo and redo; Tab indents, Ctrl+/ comments). The editor is never split: in the Bridge a short note in the pane head says the other tabs update as you type (lingo and matho update the pseudo, and the pseudo the Mojo made from it), and clicking a line marks the lines it became in the next tab down; Hardware does the same between Mojo and x86-64. Drag the dividers to resize (double-click resets); the widths, the dock tab, and what is folded are remembered in the share link.
- **The side column** is the inspect panel. Its tabs are offered only when they mean something for the pane (Prove for the pseudo family) and dimmed, with the reason, when the run has nothing for them yet.
- **The Run view** (the first tab, in the Bridge and the Developer area; `src/core/runview.ts`, drawn by `src/ui/views/run.ts`) is the whole run read top to bottom, one row per step: its number, its line, what ran (indented by call depth, with what it printed), and a column for each variable you **follow**, holding its value after that step: in color where the step wrote it (with the position, `[5, 6]`, when it wrote one element), faded where it carries over, underlined where the step reads it, hatched where it is not in scope. The lifecycle of the value a variable names (Mojo: made ●, copied ⧉, moved in ⇢, moved out ⇥, destroyed ✕) is marked in the same cell; events of values no column names are noted beside the step. Above the rows, the followed variables as they stand at the stepper's position, with a ruler for a string or list and a grid for a table, the element just written and the one about to be read marked. **+ variables** opens a picker of every variable in the run, by routine; until you choose, it follows the variables of the routine that does the most work. The choice is kept per area (`layout.follow`). "Only steps that change something" hides the rest. Click a row to step there; the stepper keeps its row in view. It replaces the Variables panel, the trace table, the table of values and the Lifetimes tab, which each showed part of this.
- **The Tests tab** is a fuzzer that shows its work (`src/core/fuzz.ts`, drawn by `src/ui/views/tests.ts`). For each routine (the pseudo's, with the speco woven in; or each Mojo function other than `main`) it lists **what each input must do** (finish within the step limit; raise no runtime error, or for Mojo no abort and no uncaught raise; keep every REQUIRE, ENSURE, INVARIANT, DECREASES and ASSERT, with inputs that break a REQUIRE skipped rather than failed; give the same answer when run again), **how the inputs were made** (each parameter's generator, with the values it tries first, and each strategy with how many inputs it made: edge cases in combination, every DNA string up to three letters for a routine that reads one, seeded random values, and mutations of the inputs that reached a line nothing earlier had reached, as a coverage-guided fuzzer does), each **failure** with the case that found it and every step of shrinking it to the smallest input that still fails the same way (**Step through this input** puts that call in the call box and shows the run), the **lines reached** by how many inputs (a line no input reached is flagged), the **answers** given and how often, and **every case** run with its strategy, input, outcome, answer or error, and steps, filterable by outcome and strategy. The seed and the number of inputs (100 to 3,000) are chosen at the top; the same seed always makes the same inputs. `tests/fuzz.test.mjs` runs it on every exercise.
- **Views that follow the run**: the **Flowchart** shades by the run so far and marks the box that runs next; the **Data flow** lights up the names the next line reads and the name the last line wrote.
- **Step colors**: every step in the Run view and the "next" box is colored by what it does (writes a value, decides, loop control, enters a routine, returns, input or output, a value destroyed, raises or fails); the legend is in the inspect panel's tab row.
- **The stepper** is docked under the editor, at the editor column's width, as part of it: first, back, step, last, play and the slider; the loop-pass jumps, run to breakpoint, predict mode, only writes, speed and CSV; the loops in flight (or the machine's counts); and what runs next. It stays visible when the dock is folded.
- **The dock** under everything holds **Setup** (the call and the input lines for pseudo, lingo and matho; the build level and stdin for Mojo; the machine and the setup block for x86-64, in fixed-size boxes), Output, Problems (with the count on its tab), Compiler (Mojo) and Machine (the Hardware area's board); ▾ folds it away.
- **Hover** any word or symbol in any editor for its reference entry: keywords, built-ins, operators, English phrasings, speco symbols, instructions, registers, condition codes.
- **Language reference** at the top of the home page, rendered from `src/core/reference.ts`. Where an engine already holds a fact (keywords, built-ins, precedence, sentence forms, instruction glosses, condition codes, machine presets) the reference reads it from the engine; the tables written by hand carry examples, and `tests/reference.test.mjs` parses every example through the real parsers, so the page cannot drift from the tool.
- **Save and load**: Share → Download writes `<title>.pplus.json`; Open… loads one back (here or on another machine). A `.pplus.json` file, a share link, or a `state=` shortcode from an earlier state format opens an empty workspace, and a save in the browser from an earlier format is discarded, so the problem opens as written; Programming+ makes no promise to keep old saves and links working. The share link and the embed code carry the same state.
- **Input**: the input box in Run setup feeds `INPUT` (pseudo) and `input()` (Mojo), one value per line; the lines travel in the share link.
## Translation between languages
Pseudo is the hub: every other notation translates to or from it, so four languages need six translators (the restructure plan, section 2.3). The translators are DOM-free functions of text under `src/sync/`; `src/sync/types.ts` has their shapes and the line maps that say which input line each output line came from.
**pseudo → Mojo** (`src/sync/pseudo-to-mojo.ts`) is one way only, and its output is always labeled generated: the first line is `# Generated by Programming+ from pseudo. Not reviewed for Mojo best practices.` (`src/sync/header.ts`). It is an app-owned port of the Mojo half of the course engine's `translate.js`, and it is deliberately literal: `var n: Int` then `n = …`, `total = total + 1`, an index loop over codepoints. Idiomatic rewrites belong to the optional best-practices helper, so a student can see the difference.
- `def main()` is written from the pseudo's own lines, then from the call being run: `COUNT_BASE('A', "GATTACA")` becomes `print(count_base("A", "GATTACA"))`, with `TRUE` as `True`, a character as a one-letter `String`, and an integer given to a `FLOAT` parameter as `1.0`.
- `raises` is inferred (a dictionary read, `input()`, `atol`, a failed `ASSERT`, or a call to a routine that raises, transitively). Imports (`Set`, `sort`, the math functions) come from the harvested standard-library index, and only for names the translation uses.
- Where the notation has a built-in with no one-line Mojo spelling (`FORALL`, `EXISTS`, `SUM`, a set written by rule, `KEYS`, `SORTED`, `SPLIT`, `FILL`, `SLICE` of a String, the statistics), the translation writes a short loop just before the line that uses it. A fixed-length `ARRAY` is an append loop, as in the verified programs, because the interpreter does not run `List(length=…)`.
- It never invents Mojo. A line with no faithful spelling (a loop condition that would need such a loop, a built-in the standard library lacks) becomes `raise Error("not translated: pseudo line N")` and a `translate-gap` warning on the pseudo line; the program stops there instead of printing a plausible wrong answer. The pseudo's own mistakes (`unsupported`) are reported, not translated.
- Two behaviors differ by design, and a literal translation keeps Mojo's: dividing a `FLOAT` by zero stops the notation but gives `nan` in Mojo, and `PARALLEL FOR` runs its passes in order with no race detector. Translation notes (`translate-divide`, `translate-each-order`, and so on) say so on the line.
`tests/sync-mojo.test.mjs` holds the translation to the pseudo: for every exercise with pseudo and every program in `tests/corpus/`, the generated Mojo has no checker errors, runs in the interpreter, and prints what the pseudo prints (compared by value, not text: `TRUE` and `True`, `3` and `3.0`, a map's keys in any order). Programs it cannot hold to that are listed in the test with a reason (the interpreter declines `chr`, `ord`, random numbers and the math functions; the checker is right about the two programs that read an unset variable), and `AGREE_AT_LEAST` is a floor that can only rise. A snapshot of the generated Mojo for every exercise is in `tests/snapshots/sync-mojo/`; when a change to the translator is wanted, run the test with `UPDATE_SNAPSHOTS=1` and review the diff.
**pseudo → lingo** (`src/sync/pseudo-to-lingo.ts`) writes the English that the lingo reader (`readSteps` in the course engine's `english.js`) understands, so the lingo pane can follow the pseudo pane. The grammar belongs to the reader, and the translator is held to it: before returning, it reads its own output back and checks that the same routines come out with the same kinds of input. If English cannot say something the way the reader needs it, the result is `unsupported` with a warning on the pseudo line, and the pane keeps its last good text instead of showing English that does not read.
- Names follow the reader's slots: a single letter or a Capitalized word. A name that is neither (`CURRENT_MAX`) has no English form yet.
- Each input is first written tersely, letting the steps show what it is. If the reader would take an input as something else, the translator adds a sentence saying what each input is ("L is a list of whole numbers.") and reads again.
- A name first set inside a block is given its value before the block, because English names are scoped by block.
- Left unsupported on purpose, each with its reason on the line: steps outside a routine (every English step belongs to a routine), records, `BYREF`, `REPEAT`, `PARALLEL FOR`, `DEFINE`, `CONSTANT`, a fixed-length `ARRAY`, maps keyed by a character, and `IN` over a String.
`tests/sync-lingo.test.mjs` holds it to that for every exercise, every corpus program, and the single-construct fixtures in `tests/helpers/sync-programs.mjs`: the English reads; lowering it back to pseudo gives a program with the same output and the same kind of stop; and writing English again from that pseudo gives the same text (comments aside). `SUPPORTED_AT_LEAST` is a floor that can only rise.
**pseudo → matho** (`src/sync/pseudo-to-matho.ts`) writes the equations, in LaTeX, for the programs that are equations, and refuses the rest. It recognizes the shapes the matho reader lowers: a `FUNCTION` that returns one value; an accumulator loop (`Total <- 0` then `Total <- Total + …`, or `1` and `*`) as `\sum` or `\prod`, with the bounds the reader uses (`FOR I <- 0 TO N` is `i=0` to `n-1`; a 1-based loop is `i=1` to `n`, and `X[I - 1]` is `x_i`); `FOR EACH` over an input list as a sum over a set; an `IF`/`ELSEIF` chain whose every branch returns as `\begin{cases}`; a call of an earlier function as a reference to its equation; and `SQRT`, `ABS`, `FLOOR`, `CEIL`, `CHOOSE`, `SIN`/`COS`/`TAN`/`EXP`/`LOG`/`LOG10`/`LOG2`, `MIN`, `MAX`, `PI()`, `DOT` and `NORM_OF`. Names given to values before the `RETURN` (the reader's hoisted calls, a temporary) are substituted where they are used.
- Everything else is `unsupported` with the construct and its line: "matho has no form for a WHILE loop (line 4)". An equation has a value, so output, input, text, a yes-or-no answer, a procedure, a record, steps outside a function, and a loop that does more than add up are all refused.
- Names. The reader makes `\bar{x}` into `X_BAR` and `\sigma` into `SIGMA`, so the pseudo has lost the student's spelling. The `NameMap` hint (`hints.names`, keyed by the upper-case pseudo name) carries it back; without one, `SIGMA` is `\sigma`, `X_BAR` is `\bar{x}`, a single letter is lower case, and a longer name is `\text{...}`. A hint is checked like everything else, and one that does not lower back to the function is refused.
- It never writes an equation that reads as something else. The LaTeX is lowered again by the matho reader and held to the pseudo: the same function names, inputs of the same kind, and the same values on three sets of sample inputs (stopping the same way where the pseudo stops). A program that fails is refused.
- Comments are not carried across. The lowering writes each equation as a comment above its function, and carrying that back would put a stale copy of the equation above the new one.
`tests/sync-matho.test.mjs` holds it to three checks on every equation set in `tests/helpers/sync-programs.mjs` (the sets `tests/matho.test.mjs` works by hand): the LaTeX reads, the pseudo it lowers to behaves like the original, and writing it again from that pseudo gives the same LaTeX. Two sets are listed as gaps with their reasons (a matrix row written `y_i`, and a second factorial whose counter the reader names `K2`); `SUPPORTED_AT_LEAST` is a floor that can only rise. Programs from the exercises and the corpus are accepted or refused the same way, with a located reason.
**The hub** (`src/sync/hub.ts`, tests in `tests/sync-hub.test.mjs`) puts the translators together. It is pure: a function of the texts it is given, with no DOM and no `localStorage`. `Session.setSource` hands an edit in a linked pane (lingo, matho, pseudo, speco) to it and applies the result in one change event; Mojo and x86-64 are stored as typed.
1. **The pane you edit is the authority** (`state.sync.authority`). The edit produces a new pseudo, directly or by lowering, and the other linked panes are regenerated from it. The pane that was edited is never rewritten, so typing never fights the cursor.
2. **Contracts ride along.** Lingo and matho cannot say contracts, so an edit in either weaves the speco into the pseudo it produced, and the speco is re-derived from that pseudo (`reconcileSpec`, which keeps claims about a routine or loop that is gone). An edit in speco replaces the pseudo's contracts with its own (`weave` in replace mode), and lingo and matho, which ignore contracts, follow.
3. **An authority with errors changes nothing.** If the edited pane does not read, every other pane keeps its text and is marked stale: "lingo line 3 does not read yet".
4. **A language that cannot say the program goes stale, not blank.** When a generator returns `unsupported` (matho has no form for a `WHILE` loop), that pane keeps its last text and is marked stale with the reason, until the program is expressible again.
5. **Mojo is produced only from pseudo**, as the literal translation, memoized by the pseudo and the call (`Session.derivedMojo()`); it is not stored.
6. **Opening a problem rewrites nothing.** Panes with text are shown as written; a linked pane that is empty is generated from the pseudo for display (`Session.source`), and reaches the saved state only with the first edit. Until then `state.sync` is absent and a pane's link state is "authored".
7. **Line maps compose through the hub.** `SyncHub.relate(maps, from, line, to)` answers which lines of one pane match a line of another, going through the pseudo; `Session.lineMaps()` has the maps of the last cascade.
`state.sync` (`{ authority, stale, names }`) is part of the saved state and the share link. It is bookkeeping, not an edit: a state whose texts are the problem's own is unedited whatever `sync` says. `names` is the student's spelling of equation names (`\overline{x}`), so a trip through pseudo restores it.
**Coverage.** `tests/sync-coverage.test.mjs` runs all three translators over every exercise, corpus program and fixture and writes [sync-coverage.md](sync-coverage.md): how many each says completely, and, for every program it cannot say, what it has no form for. Each translator has a floor in the test.
## Mojo
The distinction that shapes it: [Mojo Quest](https://quest.mojolang.org) teaches you to *write* Mojo, with the compiler as the judge; Programming+ shows you what Mojo *does when it runs*: every step, the life of every value (made, copied, moved, borrowed, destroyed), and the instructions the processor executes. The + is those views.
Everything is pinned to **Mojo 1.1.0** and checked against the real compiler on [Compiler Explorer](https://godbolt.org) (`mojo_1_1_0`). Programming+ ships no compiler and never claims a program compiles without asking one.
**The Mojo pane** is edited like the pseudo: highlighting built from the compiler's own token table (docstrings across lines, the ownership words `imm`/`mut`/`out`/`deinit`/`var`/`ref`, the transfer `^`, and the words 1.1.0 removed, such as `fn`, underlined), the VS Code extension's indentation rule, Ctrl+/ for comments, and hover text for the ownership vocabulary. Before compiling, Programming+'s own checker (`src/mojo/`) reports what it is certain the compiler would: code at file scope, an empty body, an untyped parameter, a method without self, no `main`, an implicit declaration, an unknown name (with the compiler's import hint), removed syntax such as `fn`, each in the compiler's own words. `tests/mojo-check.test.mjs` scores it against godbolt: it may never report an error on a program the compiler accepts, or one the compiler did not make. Code it cannot read yet gets a note, not an error.
**Compile & run** (Ctrl+Enter on the Mojo pane) sends the program to godbolt.org in one request: the compiler's answer, the program's output (the input box feeds `input()`), and the listing. The **Compiler** view shows them. The compiler's messages land on their lines with its fix-its as one-click fixes (an implicit copy offers "transferring the value with '^'" or "copy it explicitly with '.copy()'"). The listing is grouped by function, your own first, in Intel syntax translated from godbolt's AT&T (or the original). **Send to x86-64 pane** puts one function, and the functions of yours it calls, on the model machine with its arguments' registers ready and the listing's read-only strings placed in memory; each call into the standard library becomes a stub that stops the run where the real program would enter the library, and says so. `docs/asm-coverage.md` is the census of every instruction compiled Mojo uses against what the machine models (everything but 256-bit AVX2), and `tests/asm-coverage.test.mjs` keeps it that way. Build "as written" (`-O0`, the default, which keeps every function you wrote) or "optimized" (what `mojo build` does: small functions fold into their callers). An edit after compiling marks the answer stale rather than showing it on the wrong lines. **Step through** runs the Mojo pane in Programming+'s own interpreter (`src/mojo/interp.ts`): line by line, with the variables it follows, what each line reads and writes, loop passes, breakpoints, and each value's lifetime, in the Run view. `tests/mojo-run.test.mjs` holds it to godbolt: on every program godbolt ran, it prints exactly what that run printed, or declines and says why.
**An exercise's Mojo** is a program in `mojo/local/`, named by the exercise's `mojoProgram`. `corpus.py verify` checks it on godbolt, and the pane's badge says "verified on Mojo 1.1.0" only when godbolt's answer passed the program's own expectation.
**The corpus** behind all of this (the compiler's own words, Modular's tested programs, our probes, and godbolt's stored answers) is described in [mojo-corpus.md](mojo-corpus.md).
## speco
The course's contracts (`REQUIRE`, `ENSURE`, `INVARIANT`, `DECREASES`) can only live inside pseudocode. The speco pane lets a student write them as a separate document, in math notation, and **weaves** them into the pseudocode before proving:
```
SPEC COUNT_BASE(B, T)
ENSURE result = |{ K ∈ [0, |T|) : T[K] = B }|
LOOP FOR I
INVARIANT Total = |{ K ∈ [0, I) : T[K] = B }|
```
`∀ ∃ Σ ∈ ∧ ∨ ¬ ≤ ≥ ≠ = |…|` lower to `FORALL EXISTS SUM IN AND OR NOT <= >= != == LENGTH(…)`. `LOOP FOR I`, `LOOP WHILE`, or `LOOP 2` names the loop an invariant belongs to. Contracts already in the pseudocode are shown in the pane and never duplicated. The proof view reports each obligation against the speco line it came from.
**Where speco is going.** The next stage lets the same claims live as comments on the pseudo and the Mojo a student already has (`# @requires`, `# @ensures`, `# @invariant` on the line they govern), so a specification never has to be a separate document. Checking is two-layered and honest about which layer answered: every claim is evaluated on every step of the interpreter's run and on the generated inputs (a runtime check: "held on 300 inputs", or the smallest input that broke it), and the claims the prover can read are handed to it, so an obligation shows as *proved*, *tested*, or *broken*, never conflated.
**Speco and pseudo are two views of one set of contracts** (`src/services/speco.ts`), and neither loses a claim:
- `extractSpec(pseudo)` reads the contracts out of the pseudo as a speco document.
- `weave(pseudo, spec)` inserts a speco's claims, never duplicating what is there. This is what the proof view uses. `weave(pseudo, spec, { replace: true })` is the other mode, for when the speco is the authority: for each `SPEC` unit it first removes the routine's `REQUIRE`/`ENSURE`/`DECREASES` and the `INVARIANT`/`DECREASES` of every loop the unit selects, then inserts the speco's. Routines and loops the speco does not name are left alone.
- `reconcileSpec(pseudo, previous)` is the speco that follows the pseudo when the pseudo is edited: what the pseudo says, plus every claim the previous speco made about a routine or loop the pseudo no longer has. Those stay, under a `// kept:` comment that says why, with a warning on their line; they return to the routine or loop when it comes back, even before the pseudo has written them. A contract deleted in the pseudo, from a spec that was not waiting, is deleted from the speco too.
These laws are tested in `tests/sync-speco.test.mjs`, for `count-base-proved`, `match-proved`, and every corpus program with contracts: `extract(weave(P, extract(P))) === extract(P)`; weaving twice changes nothing; a speco woven into the same pseudo with its contracts removed, then extracted, comes back (and the contracts written are the original's, up to spelling); and reconciling is a fixed point. Holding the laws found one bug, now fixed: a symbol just inside a bracket, `(∀ K …)`, was lowered to `( FORALL K …)`, so the text drifted by a space on every round trip.
## Known limits
- The engines are the course's modules as they stand, including the issues in the toolchain review (no engine tests of their own, two unsound verifier rules, English lowered through text). Fixes belong in the engines, upstream; this app will pick them up by re-vendoring. The vendored copy carries a few small changes, each listed in [engines.md](engines.md): the four text built-ins `SPLIT`, `JOIN`, `INDEX_OF`, `REPLACE` (lang, check, interp, translate, vcgen), the numerical built-ins and `PARALLEL FOR` with its race detector (lang, parse, check, interp, translate, vcgen), an indexed read `L[I]` recorded as a read of one position rather than of the whole of `L` (interp), and a single `reserved-name` error for a keyword used as a name (parse); and three earlier ones: `english.js` exports `COMPARISONS` and `IN_PHRASES` so the reference can read them; `analyze.js` tags a variable passed to a `BYREF` parameter and `coach.js` no longer reports it as "read before set" when the procedure writes the parameter before reading it (an out-parameter); and `coach.js` no longer warns "growing bound" on a `WHILE LENGTH(Q) > 0` whose body also `REMOVE`s from `Q` (a queue).
- The assembly pane takes the course's Intel-syntax subset; directives and `[rip + label]` are not supported yet.
- Student work persists in the browser only.
+49
View File
@@ -0,0 +1,49 @@
# The model machine against compiled Mojo
"Open in Hardware" puts a function from the real compiler's listing on the model machine (`src/engines/asm86`), translated from godbolt's AT&T syntax by `src/mojo/att.ts`. The machine implements a teaching subset of x86-64, so the question is how much of what the Mojo compiler actually emits it can take. This is the census: every function in every listing the corpus holds (`mojo/golden/*.json` answered with `asm`), sent exactly as the button sends it, and what the assembler said. `node scripts/asm-census.mjs` reruns it (add `--ops` for every mnemonic); `tests/asm-coverage.test.mjs` holds the numbers as a ratchet, so a new corpus item that brings a new instruction fails the build rather than a student's session.
## Where it stands
| | before | now |
|---|---|---|
| distinct instructions in the listings | 97 | 97 |
| of which outside the model's set | 38 | 5 (all 256-bit AVX2: `vextracti128`, `vinserti128`, `vpblendvb`, `vperm2i128`, `vpalignr`) |
| the user's own functions that assemble | 3 of 7 (`main` never did) | 7 of 7 |
| standard-library and runtime functions that assemble | — | 438 of 467 |
`main()` now steps 25–29 instructions and stops at the call into `print` with "stopped: std_io_io_print: standard library, not on the model machine", which is the honest answer: the model has no standard library, and says exactly where the real program would enter it.
## What was wrong, and what changed
**The translator dropped size suffixes only for the mnemonics it knew.** AT&T writes `andnq`, `mulxq`, `shlxq`, `xaddq`, `cmpxchgq`, `btsq`, `bswapq`; the Intel pane reads `andn`, `mulx`, … The BMI and atomic mnemonics were missing from the suffix table, so the machine was asked for an instruction called `andnq`, which exists nowhere. They are in the table now, and `lock` (a prefix) is passed through as a prefix rather than treated as a mnemonic with an operand called `xaddq`.
**The machine lacked the instructions the optimiser likes.** Added, each with a one-sentence gloss for the datapath view and the micro-op model told what it reads and writes:
- BMI1/BMI2: `andn`, `mulx`, `shlx`, `shrx`, `sarx`, `bzhi`, `blsr`, `blsi`, `blsmsk`, `rorx`, `bextr` (`pdep`/`pext` are named as not modelled)
- the atomics behind reference counts: `xadd`, `cmpxchg`, and the `lock` prefix, accepted on the read-modify-writes the ISA allows it on
- bit tests that write: `bts`, `btr`, `btc`; `bswap`; `cwd`, `cwde`, `cbw`
- `ud2`: the trap the compiler plants on paths that must never run; reaching it stops the run with "the processor raised an invalid-opcode fault"
- the 128-bit AVX spellings of what the subset had: `vmovdqu`, `vmovdqa`, `vmovups`, `vmovaps`, `vmovd`, `vmovq`, `vpxor`, `vxorps`, `vpor`, `vpand`, `vpandn`, `vpaddb`, `vpsubb`, `vpcmpeqb`, `vpmovmskb`, `vzeroupper`; three-operand form (`vop dst, a, b`), sources untouched
- lanes: `vpinsr{b,w,d,q}`, `vpextr{b,w,d,q}`, `vpshufb`, `vpshufd`, `vpbroadcast{b,d}`, `vpmin/max{ub,ud}`, `vpcmpeq{w,d,q}`, `vpadd{w,d}`, `vpsubd`, `vpsubusb`, `vpsll/vpsrl{w,d,q}`
**A call into the standard library refused the whole listing.** The assembler resolves every label up front, so one `call std::io::print` meant the function could not be stepped at all, even to the instruction before the call. The translator now appends a stub for every such symbol (`label:` then `ud2 ; …: standard library, not on the model machine`), so the function assembles, steps up to the call, and the stop says what it called.
**Read-only strings were unreachable.** `lea rax, [rip + static_string_…]` named a label that was data, not code, and the machine has no data directives. The translator now finds the `.asciz` behind each such label, places the bytes in memory (`memory 0x6000 "…"`, octal and hex escapes decoded, from 0x6000 up), writes the address in the instruction's place, and hands the lines to the setup block, where the student can see them.
## Scalar doubles, parity, shld (added)
- `addsd subsd mulsd divsd sqrtsd movsd cvtsi2sd ucomisd comisd` and their `v` forms: IEEE binary64, round to nearest even, default NaN `0xFFF8000000000000`, a NaN operand is quieted and the first operand wins. MXCSR exception flags are not modelled.
- `ucomisd`/`comisd` set ZF/PF/CF as hardware does (unordered sets all three; OF, SF clear).
- PF is a real flag now: set by logic, add/sub and shifts, cleared by `popcnt`, untouched by rotates. `jp jnp jpe jpo`, `cmovp…` and `setp…` follow.
- `shld`/`shrd` on 32- and 64-bit operands; count masked to 5/6 bits; count 0 changes nothing, flags included.
- Latencies: add/mul 4, div 14, sqrt 18 (unpipelined on port 0), convert 5, compare 3.
## What stays outside, and why
- **256-bit AVX2 (`ymm`)**: the model keeps sixteen 128-bit `xmm` registers and no `ymm` halves; the five instructions above exist only in that width. A `ymm` operand is refused with that sentence. Modelling it means widening every vector register and every lane helper; worth doing only when a user function needs it, and none in the corpus does.
- **Symbols the listing addresses but does not define**: `KGEN_…` runtime globals, `…@GOTPCREL` function pointers, a `.zero` constant. The assembler names the symbol in its refusal.
- **Constant-pool blocks with a symbol in them** (jump tables): not placed; the instruction that loads one is refused by name. Numeric `.LCPI…` blocks (`.quad`, `.long`, `.double`, `.zero`, …) *are* placed, 16-byte aligned from 0x6000, when the code addresses them, and `.LCPI0_0+8(%rip)` works.
## Keeping it honest
The census runs against whatever the corpus holds. Seven goldens carry listings today (the `asm`/`both` probes); `pixi run mojo-verify` with `mode: asm` probes adds more, and each addition either assembles or fails `tests/asm-coverage.test.mjs` with the instruction named. The ratchet numbers in that test are the ones in the table above; raise them when the machine learns more, never lower them.
+34
View File
@@ -0,0 +1,34 @@
# Deploying
`pixi run site` tests the app and assembles `site/`; `pixi run deploy [slug] [user@host]` does that and publishes it. CI (`.gitea/workflows/deploy.yml`) does the same on every push to `main`.
The site is five things: `index.html`, `styles.css`, `styles/` (the course's widget styles, which the Hardware area's machine views use), `dist/`, and the Quarto extension (`quarto/_extensions/pplus`, without an engine copy), which the With Quarto page loads (`pplus.css`, `pplus.js`) and links to file by file. `scripts/assemble.sh` copies them into `site/` with a `VERSION` file holding the commit, and `scripts/deploy.sh <slug> [user@host]` publishes `site/` to `/srv/www/<slug>` as an atomic release:
```
/srv/www/pplus -> symlink to the live release
/srv/www/pplus.releases/ one directory per deployed commit, the five newest kept
```
The swap is one rename, so nobody sees a half-copied site, and a rollback is `ln -sfn /srv/www/pplus.releases/<sha> /srv/www/pplus`. A pre-existing plain directory at `/srv/www/<slug>` is moved to `<slug>.releases/before-releases` on the first run.
**Caddy**: [`Caddyfile`](Caddyfile) is the site block (root on the symlink, `file_server`, `no-cache` on the modules so a new deploy is picked up on the next load, 404s rewritten to the app, and `frame-ancestors` so course pages can embed views). The live shortcodes and `live="click"` put the app in an iframe, so a Quarto site on another origin needs that origin added to `frame-ancestors`; the rendered views need nothing from the host. Caddy issues the certificate itself; add the block to `/etc/caddy/Caddyfile` and `systemctl reload caddy`.
**Gitea Actions without a container image** (`.gitea/workflows/deploy.yml`): the act_runner on the droplet runs jobs on the host shell instead of in docker. Once, on the droplet:
```bash
# tools the job uses
apt install -y git rsync curl
curl -fsSL https://deb.nodesource.com/setup_22.x | bash - && apt install -y nodejs # or any node >= 20
# a user for the runner that owns the web root
useradd -m -s /bin/bash deploy
mkdir -p /srv/www && chown deploy:deploy /srv/www
# register the runner with a host-mode label (the :host suffix is the whole trick)
sudo -u deploy act_runner register --instance https://<your-gitea> --token <runner token> --labels "quarto-deploy:host" --no-interactive
# run it as a service (act_runner generate-config > config.yaml; systemd unit per the Gitea docs, User=deploy)
```
With that label, `runs-on: quarto-deploy` executes steps directly as `deploy`, with the host's node, git, and rsync; `actions/checkout` works because node is on the host, and no image is pulled. The job builds, runs the tests, checks that our Mojo programs pass (`corpus.py status --strict`, offline), assembles `site/`, and on `main` runs `scripts/deploy.sh` into `/srv/www`. `SITE_SLUG` (repository variable) names the directory and defaults to the repository name; set it to `pplus`. `SITE_URL` turns on a smoke test that fetches `/VERSION` from the live site and fails the job if it is not the deployed commit.
If the runner ever moves off the droplet, `scripts/deploy.sh pplus deploy@droplet` rsyncs over SSH instead; give that runner a key whose public half is in `deploy`'s `authorized_keys`.
By hand, on the droplet: `pixi run deploy pplus`. From elsewhere: `pixi run deploy pplus deploy@droplet`.
+31
View File
@@ -0,0 +1,31 @@
# The vendored course code
Programming+ runs the course site's own language engines and draws the hardware views with the course's own stylesheets, so a program behaves the same in the app as on a course page.
| Here | From the course repository | What it is |
|---|---|---|
| `src/engines/pseudo/` | `static/js/pseudo/` | The pseudo language: parser, checker, interpreter, the English (lingo) reader, the prover's verification conditions, translation |
| `src/engines/asm86/` | `static/js/asm86/` | The x86-64 model machine, its caches, pipeline and out-of-order core, and the widgets that draw them |
| `src/engines/shared/` | `static/js/shared/` | DOM helpers, URL state, text distance, charts |
| `styles/course/` | `static/css/base/`, `static/css/widgets/` | The widget stylesheets ([styles/course/README.md](../styles/course/README.md)) |
The engines are wrapped behind one `LanguageService` interface (`src/core/types.ts`, adapters in `src/services/`). Modules the app does not use are excluded from the build in `tsconfig.json`. Do not edit `src/engines/` casually: a change there is a change to the course's language.
## How the copies differ from the course
`pixi run engines-diff <course>/static` compares every file, ignoring whitespace. As of the last check the stylesheets are identical; most engine modules differ only in formatting (they were reindented); and fourteen differ in content, every one of them a change made here and not yet sent back:
- **pseudo:** the text built-ins `SPLIT`, `JOIN`, `INDEX_OF`, `REPLACE` and the numerical built-ins (`FLOOR`, `CEIL`, `LOG10`, `SIN`, `COS`, `TAN`, `ATAN2`, `PI`, the statistics) in `lang`, `parse`, `check`, `interp`, `translate`, `vcgen`; `PARALLEL FOR` with its race detector; an indexed read `L[I]` recorded as a read of one position, not all of `L` (`interp`); one `reserved-name` error for a keyword used as a name (`parse`); `english.js` exporting `COMPARISONS` and `IN_PHRASES` so the reference can read them; `analyze.js` and `coach.js` treating a variable passed `BYREF` to a procedure that writes it first as an out-parameter, not a read; and `coach.js` no longer warning "growing bound" on a queue drained by `WHILE LENGTH(Q) > 0`.
- **asm86:** what compiled Mojo uses beyond the course's subset (`interp.js`, about 630 lines): the BMI bit instructions, atomic read-modify-writes with `lock`, bit tests that write, `bswap`, `ud2`, the 128-bit AVX spellings, scalar double precision, and the double-width shifts; the parity flag (`interp`, `uops`, `views`); the floating-point units and their latencies (`uops`); a small change in `sandbox.js`; and in `hwviews.js` the whole core's arrows (`machineView`): only a lit edge carries an arrowhead, in its own color and on the end its data reached, each view has its own marker ids, and the result's edge into the registers starts at the port that produced it.
One addition to the pseudo language lives outside the engine, in app code: `DECLARE <name> : <type> <- <value>`, a declaration with its starting value on one line (Mojo's `var total: Int = 0`). `src/services/pseudo-study.ts` reads it by doing what the engine's `study()` does (parse, check, analyze, coach) with one step between parse and check: the `<- value` is blanked out of the line, columns kept, so the engine parses a plain DECLARE, and the value is parsed on its own and put in as an ordinary assignment on the same line. Every app reader of pseudo (`studyOf`, and the lingo, matho and Mojo translators) goes through it; pseudo-to-mojo writes the pair as one `var` line. The two-line form reads as before. If the course takes the form into its parser, this module can go.
Deciding what happens to these (send them to the course, or make this repository the engines' home and have the course copy from here) is open; until then, `engines-diff` is how to see the gap.
## Updating from the course
1. `pixi run engines-diff <course>/static` and read the list.
2. For a file that differs only in whitespace, or that changed only on the course side, copy the course's file over the one here.
3. For a file that differs in content on both sides, merge by hand, keeping the changes listed above.
4. `pixi run test`. The engines have no tests of their own in the course repository; the tests here (`tests/services.test.mjs`, `tests/corpus.test.mjs`, the curriculum and reference tests, `tests/asm-coverage.test.mjs`) are what catch a regression.
5. For the stylesheets, follow [styles/course/README.md](../styles/course/README.md).
+38
View File
@@ -0,0 +1,38 @@
# Adding an exercise
An exercise is a catalog problem: one file in `src/exercises/`, listed in `src/exercises/index.ts`. The home page, the problem menu, share links, embeds, and the tests pick it up from there. `pixi run test` checks every exercise: its pseudo parses, its call runs, its answer matches `expect`, and its Mojo program (if it names one) exists and prints what it should.
There are two ways to start one.
## An exercise around a Mojo program
```bash
pixi run new-exercise rolling-sum # mojo/local/rolling-sum.mojo, src/exercises/rolling-sum.ts, registered
pixi run play rolling-sum # after each edit: run, verify on godbolt, build, list the assembly, test
```
For a title or a home-page section other than the defaults, run the script directly: `node scripts/new-exercise.mjs rolling-sum --title "Rolling sum" --group "Loop forms"`. If `mojo/local/rolling-sum.mojo` already exists, it is kept as written and only the exercise is made.
The exercise names its program (`mojoProgram: 'rolling-sum'`) instead of carrying the source. The Mojo pane shows the file without its header comments, and badges it "verified on Mojo 1.1.0" only when godbolt's answer for that exact source passed the file's own `# expect-stdout:` lines. Editing the file changes its key, so it reads as unverified until `play` (or `mojo-verify`) asks again. The header keys are in [mojo-corpus.md](mojo-corpus.md#mojo-of-our-own).
With `# mode: both` and `# args: -O0 --debug-level=line-tables` in the header, godbolt also returns the listing, and `play` turns it into the exercise's x86-64 pane (see "The assembly" in [mojo-corpus.md](mojo-corpus.md#the-assembly)).
## An exercise in lingo, pseudo, matho or speco
Copy `src/exercises/_template.ts` to `<id>.ts`, fill it in, import it in `src/exercises/index.ts`, and add it to the list (before `blank`, the demo playground, which stays last). Then `pixi run test`.
## The fields
| Field | Means |
|---|---|
| `id` | The URL (`#/<area>/p/<id>`): lowercase words joined by hyphens |
| `title`, `group`, `blurb` | The name, the home-page section it files under (a new name makes a new section), and one or two sentences on what the student does |
| `meta` | Optional: `lecture`, `level` (`intro`, `core`, `advanced`), `tags`, `concepts`, `minutes`, `page` (where it is taught) |
| `sources` | Any of `lingo`, `pseudo`, `matho`, `speco`, `asm`. Pseudo is derived from lingo (or matho, written in LaTeX) when absent, and speco from the pseudo's inline contracts |
| `mojoProgram` | The name of a program in `mojo/local/`, shown in the Mojo pane |
| `call`, `expect` | The call to run, and what it should return; the tests compare them |
| `setup`, `machine` | For assembly: the setup block (registers and memory before the run) and the machine model preset |
| `lang` | The pane that opens first |
| `area` | The area it opens in: `bridge`, `dev` or `hw`. Absent: Hardware for `asm-*` ids, Developer for a problem that is only a Mojo program, Bridge otherwise |
`src/exercises/types.ts` documents each field in full.
+141
View File
@@ -0,0 +1,141 @@
# The Mojo corpus
Programming+ teaches what Mojo does when it runs, so everything it says about Mojo has to be true of a real compiler at a known version. The corpus is how: material harvested from Modular's own repositories at pinned commits, plus small programs of our own, every one of them checked on the real compiler through Compiler Explorer (godbolt). The pipeline is Python, standard library only, in `scripts/mojo/` (`corpus.py` is its command line); Node is needed for one processor (Mojo Quest keeps its tickets in TypeScript).
Every command below is a pixi task; the [README](../README.md#commands) lists them all.
## Mojo of our own
There are three kinds of Mojo program we write, and each has a folder, a task to start one, and a job:
| Kind | Folder | Start one | Its job | Shipped in the app |
|---|---|---|---|---|
| probe | `mojo/probes/` | `pixi run new-probe <name> "<question>"` | Ask the pinned compiler one question (what does `//` do on a negative Int?). Godbolt's answer is the point; it is recorded, not judged. | no, but the checker and interpreter are held to the answers |
| exercise program | `mojo/local/` | `pixi run new-exercise <id>` | The Mojo of a catalog problem. It must pass its own `# expect-stdout:` lines. | yes, in `src/mojo/generated/programs.ts`, badged verified when it passed |
| stress program | `mojo/stress/` | `pixi run new-stress <name> "<what it exercises>"` | Realistic Mojo that stresses the interpreter. Its `# expect-stdout:` lines are the interpreter's prediction; godbolt confirms or refutes it. | no |
The loop is the same for all three:
```bash
pixi run new-probe int-floordiv-negative "does // floor toward negative infinity on Int?"
# edit mojo/probes/int-floordiv-negative.mojo
pixi run mojo-verify-item 'probes/int-floordiv-negative' # ask godbolt (network)
pixi run test # the checker and interpreter scoreboards read the new answer
```
For an exercise program, `pixi run play <id>` does the whole loop in one pass (below).
### The header
A program starts with comment lines that `corpus.py verify` reads. Only these keys are header lines; the program starts at the first other line, and the Mojo pane hides the header.
```mojo
# probe: what does // do on negative Int? the question, or what the program shows (one line)
# stdin: 3\n4\n what input() reads, with \n escapes
# mode: run run | asm | both (asm and both also return the listing)
# args: -O0 compiler arguments
# expect-stdout: -4 a line the program must print (repeatable); implies expect: pass
# expect: compile-error pass | fail | compile-error | observe (the default without expect-stdout)
# origin: where the program came from free text, for people
# status: a note on its state free text, for people
```
**A stored answer belongs to the exact text.** Godbolt's answer is keyed by the compiler, mode, arguments, stdin and the whole source, header included. Any edit, even to a comment, makes the program unverified until it is asked again. That is deliberate: a stale answer is never shown against new code.
### The fast loop for an exercise program
```bash
pixi run play rolling-sum # one pass
pixi run play-watch rolling-sum # again on every save (tests off)
```
One pass is: run the file on the local `mojo` (pixi provides it); `corpus.py verify --item local/<name>` (godbolt, network); `corpus.py status` (offline, rewrites `programs.ts`); `tsc`; `scripts/mojo/listings.mjs`; the tests. A step that cannot run (no local compiler, godbolt unreachable) is reported as skipped and the pass goes on, so offline you still get the build and the tests, with the program shown as unverified rather than guessed at. `node scripts/play.mjs <name> --no-verify` or `--no-test` skips a step.
### The assembly
A program whose header says `# mode: both` (or `asm`) and `# args: -O0 --debug-level=line-tables` makes godbolt return the compiler's listing with its answer. `scripts/mojo/listings.mjs` picks the first `def` that is not `main`, translates it and the user functions it calls to the x86-64 pane's syntax exactly as the **Send to x86-64 pane** button does (`src/mojo/att.ts`, `simulatorSetup` for the argument registers), tags each instruction `; mojo line N` with the line of the program the pane shows, and writes `src/mojo/generated/listings.ts`. An exercise that names the program in `mojoProgram` and leaves `sources.asm` empty gets that listing and its setup. No answer for the exact source, mode and arguments means no listing; a stale answer is never reused, because the key includes the source. Without `-O0` the optimizer may inline every function and the listing holds none of yours; the script says so.
Header lines (`# probe:`, `# mode:`, …) are for `verify`; only those keys are stripped from what the Mojo pane shows. The first line after the header block is the program.
## Reading the status
`pixi run mojo-status` judges every item from the stored answers, offline, and writes `mojo/golden/STATUS.md` (a table per corpus, every failure with its reason, and every probe's question and verdict) and `status.json` (`git diff mojo/golden/status.json` shows exactly what changed).
Each item says what the pinned compiler should do with it: `pass` (compiles, runs, exits 0, and prints what it should or contains the idiom it should), `fail` (that check must not hold: a starter), `compile-error` (must be rejected, with each expected error at its line), `observe` (a probe: the answer is the point), or `skip` (with a reason: newer syntax than the pin, no `main`, not reproducible on public godbolt). Verdicts are `pass`, `fail`, `observed`, `skipped`, and `unverified` (no golden yet).
The dialect markers in the pin are a cheap first look: `newer` patterns are syntax that arrived after the pinned version (a manual sample using one is skipped), `older` patterns are syntax the pinned version rejects. They only set expectations; verify decides.
**What has to pass.** `pixi run mojo-status-strict` (and CI) fails only when a program we wrote fails: a probe, an exercise program, or a stress program. Harvested items can fail for reasons that are facts about upstream (a manual sample written for a newer compiler, a test file with no `main`); they are listed in `STATUS.md` to read, not to fix here. `corpus.py status --strict --strict-corpus all` holds every corpus to it.
## What lives where
| Path | What it is | Who writes it |
|---|---|---|
| `mojo/pin.json` | The Mojo version, the godbolt compiler id, each source repository and the ref to use, and the dialect markers | You |
| `mojo/mojo.lock.json` | What each ref resolved to: commit, zip sha256, and the directory inside the zip | `fetch`/`harvest` |
| `mojo/corpus/` | Processed material, one directory per processor, each item with its provenance | `harvest` |
| `mojo/corpus/SOURCES.md` | Which commit and license everything came from, what each processor found, every warning | `harvest` |
| `mojo/probes/` | Our questions about the pinned compiler's behavior, one small program each | You (`new-probe`) |
| `mojo/local/` | Exercise programs, shipped in the app | You (`new-exercise`) |
| `mojo/stress/` | Realistic programs that test the interpreter, not shipped | You (`new-stress`) |
| `mojo/golden/<key>.json` | Godbolt's answer for one program, keyed by compiler, mode, arguments, stdin and source | `verify` |
| `mojo/golden/STATUS.md` | Every item's verdict against the goldens | `status` (also `harvest`, `verify`) |
| `src/mojo/generated/` | What the app reads at run time: `pin.ts` (version, compiler), `tokens.ts` (the words, removed words and the compiler's messages for them), `editor.ts` (comment and indentation rules), `programs.ts` (`mojo/local/` programs with their verdicts), `stdlib.ts` and `types.ts` (which package exports each name, which types are copyable), and `listings.ts` (exercise listings, written by `scripts/mojo/listings.mjs` during `play`) | `harvest`/`emit`; `verify` and `status` refresh `programs.ts` |
| `quarto/_extensions/pplus/syntax/mojo.xml` | The same words as a KDE syntax for Pandoc listings | `harvest`/`emit` |
Commit all of it. The stored answers are what make `pixi run test` and `mojo-status` work offline.
## Commands in detail
The tasks wrap `corpus.py`, which takes more options than the tasks pass:
- `harvest --local NAME=ZIP` uses a zip on disk for one source. `--local-dir DIR` matches every zip in a directory to a source by its marker files, but only for sources whose ref is still `UNRESOLVED`; add `--offline` to let zips stand in for pinned refs too (the lock then says `standsInFor`, and the next online run fetches the real ref).
- `harvest --processors quest,tokens` reruns some processors; `--keep` or `--workdir DIR` keeps the extracted sources for inspection.
- `verify --item 'probes/life-*' --force` asks again about some items (`pixi run mojo-verify-item` does this); `--dry-run` shows the request and the count and sends nothing; `--corpus diagnostics` adds the compiler's own tests (opt-in: about 140 files); `--limit N` asks about at most N.
- `status --strict` exits 1 if a program we wrote fails; `--strict-corpus` picks other corpora.
- `GITHUB_TOKEN` (any token with public read access) avoids GitHub's anonymous rate limit when resolving refs.
## The processors
| Processor | From | Produces |
|---|---|---|
| `quest` | mojo-quest | Each ticket's solution (must pass Mojo Quest's own check) and starter (must not) |
| `manual` | modular | The manual's tested code samples (must run and exit 0) and every `mojo` block that is a whole program followed by an `output` block (must print it) |
| `diagnostics` | modular | The compiler's `expected-error/warning/note` tests, each annotation resolved to its line and tagged with the pass that reports it (`parser`, `lifetimes`) |
| `tokens` | modular | Keywords (`TokenKinds.def`), soft keywords and removed words (the parser), decorators (the reference), prelude names (the stdlib) |
| `messages` | modular | The parser's and borrow checker's diagnostic wording and fix-its, read from their C++ |
| `release` | modular | The pinned release notes, section by section, and whether the snapshot is the pin, newer, or older |
| `syntax` | mojo-syntax | The TextMate grammar's tests as plain highlighting cases |
| `editor` | vscode-mojo | Comments, brackets, auto-closing pairs and indentation rules |
| `skill` | skills | Modular's table of removed syntax and its replacements |
| `stdindex` | modular | Which std package exports each public name (`sqrt` in `std.math`), for the compiler's import hint; a name exported from two places is left out; and which prelude functions raise (`input`, `atol`) |
| `stdtypes` | modular | Each std struct's declared traits (so which are implicitly copyable) and each trait's default methods (Copyable's `copy`, Equatable's `__eq__`), for the type checks |
A processor whose input files are missing at the pinned ref is skipped with a warning, and its previous output is kept.
## Moving to a new Mojo version
1. Find the release. Mojo releases are tagged `mojo/vX.Y.Z` in `modular/modular` (the platform's own tags are `modular/vX.Y`). Find godbolt's compiler id for it, `mojo_X_Y_Z`, in `https://godbolt.org/api/compilers/mojo`.
2. Edit `mojo/pin.json`: `mojo.version`, `godbolt.compiler`, and `sources.modular.ref`. Move the other refs to the commits that match: Mojo Quest's commit whose `src/lib/compile.ts` names the new compiler id; the vscode-mojo, mojo-syntax and skills commits released alongside it.
3. Review the dialect markers against the new release notes. Anything in the notes' **Removed** or **Language changes** sections belongs in `older`; anything in `newer` that this release now includes comes out. (`newer` matters only when harvesting a snapshot past a release.)
4. `pixi run mojo-harvest`, then read `mojo/corpus/SOURCES.md`: every warning is something to look at, and a `release` line saying `snapshot newer` means the ref is not the release tag.
5. `pixi run mojo-verify`. A new compiler id changes every key, so every item is asked again: about 440 requests, two at a time. Run it once, not in a loop; the public server is shared.
6. `pixi run mojo-status`, then read `mojo/golden/STATUS.md`. `git diff mojo/golden/status.json` shows exactly which verdicts and probe answers changed between versions. A changed probe answer is a change Programming+'s Mojo engine has to make; a failing Mojo Quest solution or manual sample usually means a language change the markers should know about.
7. `pixi run test`, then commit the pin, the lock, the corpus, the goldens, and `src/mojo/generated/` together.
## Licenses and provenance
Every item records its repository, commit (or local zip hash), path, and license; `SOURCES.md` summarizes them. Modular's repository files carry Apache-2.0 WITH LLVM-exception headers. Mojo Quest's files carry the same headers, but the repository has no LICENSE file, so its programs are used as test fixtures here; confirm with Modular before showing them to students as exercises. mojo-syntax is MIT, vscode-mojo is Apache-2.0. Manual prose is not copied into the app; hover text and quick fixes will be written in our own words and link to mojolang.org.
## When something goes wrong
| Message | Meaning |
|---|---|
| `a network proxy refused api.github.com` | No route to GitHub from here. Use `--local-dir DIR --offline`, or run elsewhere. |
| `GitHub refused the request (403)` | Usually the anonymous rate limit. Set `GITHUB_TOKEN`. |
| `GitHub has no ref ...` | The tag or commit in the pin does not exist. |
| `the lock was made from a local zip` | The pin has not moved since a local harvest. Pass the same zip with `--local`, or set a ref. |
| `GitHub's zip ... hashes to ...` | The archive for a locked commit changed. Rare; accept it with `--allow-hash-change` after a look. |
| `no directory in the zip holds all of [...]` | The repository's layout changed. Update that source's `markers` in the pin. |
| `<processor>: skipped, ... has no ...` | That input is missing at this ref; the previous output is kept. |
| `the quest processor needs Node 22.6+` | Node strips the TypeScript types from Mojo Quest's ticket file. |
+115
View File
@@ -0,0 +1,115 @@
# Translation coverage
<!-- Written by tests/sync-coverage.test.mjs. Do not edit; rerun `npm test` to refresh. -->
Each translator in `src/sync/` is run over every exercise with pseudo (17), every program in `tests/corpus/` (48), and 17 one-construct fixtures (`tests/helpers/sync-programs.mjs`). 3 of the 82 have pseudo that does not read, by design (they teach the notation's error messages), and are left out below. That leaves **79 programs**.
| From pseudo to | Says it completely | Says it with a gap or a checker error | Cannot say it |
| --- | ---: | ---: | ---: |
| Mojo | 77 | 2 | 0 |
| lingo | 31 | 0 | 48 |
| matho | 3 | 0 | 76 |
Mojo is a program-for-program translation that always produces something: a line with no faithful spelling becomes a visible `raise Error("not translated: pseudo line N")` and a warning. Lingo and matho must read back as the same program, so what they cannot say exactly they refuse, with the construct and its line, and the pane keeps its last good text.
## Mojo: lines that become a visible gap
These programs translate, with the listed lines left as a `raise Error`.
Nothing.
## Mojo: programs the translator refuses
Pseudo the course itself rejects is not translated.
Nothing.
## lingo: what English has no sentence for
English is read by `readSteps`, whose grammar has no sentence for these.
| What it has no form for | Programs | Which |
| --- | ---: | --- |
| steps outside a routine (every English step belongs to a routine) | 46 | 01-arithmetic.pseudo, 02-temperature.pseudo, 03-compound-interest.pseudo, 04-gcd-recursion.pseudo, and 42 more |
| a fixed-length ARRAY | 4 | ex:edit-distance, 05-primes-sieve.pseudo, 11-matrix-multiply.pseudo, 15-game-of-life.pseudo |
| a BYREF parameter | 3 | 06-fibonacci-memo.pseudo, 10-insertion-sort.pseudo, 26-swap-byref.pseudo |
| a HASHMAP whose values are not counts | 3 | ex:translate-codons, 13-stack-brackets.pseudo, 39-constants-codons.pseudo |
| a change to this part of a value | 2 | ex:edit-distance, 16-running-stats.pseudo |
| a DEFINE set | 2 | ex:translate-codons, 21-sets.pseudo |
| a loop step that is not a whole number written out | 2 | 05-primes-sieve.pseudo, 39-constants-codons.pseudo |
| a record | 2 | 12-records.pseudo, 16-running-stats.pseudo |
| a record type | 2 | 12-records.pseudo, 16-running-stats.pseudo |
| REMOVE(...) | 2 | 13-stack-brackets.pseudo, 14-queue-bfs.pseudo |
| the built-in ROWS | 2 | 11-matrix-multiply.pseudo, 15-game-of-life.pseudo |
| this kind of position | 2 | ex:edit-distance, 15-game-of-life.pseudo |
| a CONSTANT | 1 | 39-constants-codons.pseudo |
| a Field value | 1 | 12-records.pseudo |
| PARALLEL FOR | 1 | 43-parallel-map.pseudo |
| REPEAT ... UNTIL, which English reads as a loop that tests first | 1 | 46-projectile.pseudo |
| the built-in CHOOSE | 1 | 47-binomial-and-ph.pseudo |
| the built-in CHR | 1 | 08-caesar.pseudo |
| the built-in COS | 1 | 46-projectile.pseudo |
| the built-in FILL | 1 | 43-parallel-map.pseudo |
| the built-in LOG10 | 1 | 47-binomial-and-ph.pseudo |
| the built-in SIN | 1 | 46-projectile.pseudo |
| the built-in SPLIT | 1 | 40-text-builtins.pseudo |
| the built-in TO_INTEGER | 1 | 22-binary-to-decimal.pseudo |
| the built-in TO_STRING | 1 | 22-binary-to-decimal.pseudo |
## matho: what is not an equation
An equation lowers to one `FUNCTION` that returns a value; a program with output, text, a loop that does more than add up, or steps outside a function is not one.
| What it has no form for | Programs | Which |
| --- | ---: | --- |
| steps outside a function (an equation is a function) | 42 | 01-arithmetic.pseudo, 02-temperature.pseudo, 03-compound-interest.pseudo, 04-gcd-recursion.pseudo, and 38 more |
| a function that answers LIST (equations answer numbers) | 5 | ex:match, ex:match-proved, ex:match-off-by-one, ex:match-reset, and 1 more |
| a function that answers STRING (equations answer numbers) | 5 | ex:revcomp, fixture:string-build, fixture:slice, fixture:case, and 1 more |
| a function that answers BOOL (equations answer numbers) | 3 | ex:binary-search, fixture:early-return, fixture:forall |
| a loop that is not adding up or multiplying one value (FOR) | 3 | ex:best-position, fixture:loop-down, fixture:break-continue |
| the input T, which is not a number or a list of numbers | 3 | ex:first-unknown, ex:gc-fraction, fixture:set |
| a DEFINE set | 2 | ex:translate-codons, 21-sets.pseudo |
| a function that answers HASHMAP (equations answer numbers) | 2 | ex:tally, ex:kmers |
| a record type | 2 | 12-records.pseudo, 16-running-stats.pseudo |
| the input A, which is not a number or a list of numbers | 2 | ex:hamming, ex:edit-distance |
| the input B, which is not a number or a list of numbers | 2 | ex:count-base, ex:count-base-proved |
| a CONSTANT | 1 | 39-constants-codons.pseudo |
| a loop with a STEP | 1 | fixture:loop-step |
| a position that is not a loop counter plus or minus a number | 1 | fixture:min-max |
| a PROCEDURE | 1 | fixture:procedure |
| a WHILE loop | 1 | fixture:div-mod |
## matho: the equation sets
Each set in `tests/matho.test.mjs` is lowered to pseudo by the matho reader, written back as equations by `pseudoToMatho`, and checked: 26 of 28 round-trip.
| Equation set | Round-trips | Why not |
| --- | :---: | --- |
| mean-and-variance | yes | |
| mean | yes | |
| sum-from-one | yes | |
| sum-no-bounds | yes | |
| binomial | yes | |
| height | yes | |
| kinetic | yes | |
| gravity | yes | |
| omega | yes | |
| normal-density | yes | |
| ph | yes | |
| log2 | yes | |
| ln-and-log | yes | |
| factorial | yes | |
| choose | no | the loop counter K2 (matho writes it as a single letter) |
| cosine | yes | |
| distance | yes | |
| matrix-row | no | a two-dimensional position that is not two loop counters |
| nested-sums | yes | |
| relu | yes | |
| piecewise | yes | |
| calls-an-earlier-equation | yes | |
| sum-over-a-set | yes | |
| floor | yes | |
| ceiling | yes | |
| absolute | yes | |
| max-min | yes | |
| mod | yes | |
+30
View File
@@ -0,0 +1,30 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Programming+</title>
<meta name="description"
content="Programming+ takes a procedure from an idea to Mojo to the machine. The Bridge translates it as you type between plain English (lingo), equations (matho), pseudo and a specification (speco), and generates labeled Mojo; Developer is for writing Mojo against the real compiler, with every step and value in view; Hardware shows the registers, caches and pipeline it runs on. Nothing to install.">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link rel="stylesheet"
href="https://fonts.googleapis.com/css2?family=IBM+Plex+Mono:ital,wght@0,400;0,600;1,400&family=IBM+Plex+Sans:wght@400;500;600;700&display=swap">
<link rel="stylesheet" href="./styles.css">
<!-- the course's widget styles, for the Hardware area's machine views (styles/course/README.md); this order -->
<link rel="stylesheet" href="./styles/course/bridge.css">
<link rel="stylesheet" href="./styles/course/tokens.css">
<link rel="stylesheet" href="./styles/course/kit.css">
<link rel="stylesheet" href="./styles/course/asm86.css">
<script>try { var t = localStorage.getItem("pplus.theme"); if (t === "light" || t === "dark") document.documentElement.setAttribute("data-theme", t); } catch (e) { }</script>
<link rel="icon"
href="data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'><style>rect{fill:%23f6c453}text{fill:%2316191f}@media (prefers-color-scheme:dark){rect{fill:%230e1117}text{fill:%23f0c05a}}</style><rect width='16' height='16' rx='3'/><text x='8' y='12' font-size='8' text-anchor='middle' font-family='monospace' font-weight='700'>P+</text></svg>">
</head>
<body>
<div id="app"><noscript>Programming+ needs JavaScript.</noscript></div>
<script type="module" src="./dist/main.js"></script>
</body>
</html>
+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
Loaded 100 of 1679 files, more files were not shown because too many files have changed in this diff. Show more