Compare commits
14
Commits
main
..
c5157fcad5
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c5157fcad5 | ||
|
|
961a59054d | ||
|
|
d4f2d92ece | ||
|
|
f400391a89 | ||
|
|
ad712a5805 | ||
|
|
d4730b7d5a | ||
|
|
9e318a1eb5 | ||
|
|
6a2973ba1f | ||
|
|
95e509660b | ||
|
|
44606bf0cf | ||
|
|
26283cd7e4 | ||
|
|
08c74c16d2 | ||
|
|
8f403226fb | ||
|
|
659c03bbf8 |
No files matched your search
@@ -1,61 +0,0 @@
|
|||||||
# pplus-core's scheduled run: the fuzzers for longer than the gate can afford, on seeds that move with the date, and
|
|
||||||
# mojo-status-strict (`pixi run nightly`). A failure opens nothing and sends nothing: the run goes red where anyone
|
|
||||||
# looking at the repository's Actions page sees it. docs/ci.md says how to reproduce a seed and what to do with it.
|
|
||||||
#
|
|
||||||
# Gitea Actions, on the `heavy` runner test.yml describes (never the deploy server); on GitHub Actions the same file
|
|
||||||
# runs with `runs-on: ubuntu-latest`.
|
|
||||||
name: Nightly
|
|
||||||
on:
|
|
||||||
schedule:
|
|
||||||
- cron: "17 6 * * *" # 06:17 UTC, before the working day in America
|
|
||||||
workflow_dispatch:
|
|
||||||
|
|
||||||
# one nightly run at a time: while no `heavy` runner is registered a run waits, and the next night's replaces it
|
|
||||||
concurrency:
|
|
||||||
group: nightly
|
|
||||||
cancel-in-progress: true
|
|
||||||
|
|
||||||
env:
|
|
||||||
CI: "true"
|
|
||||||
PIXI_VERSION: "0.83.0"
|
|
||||||
|
|
||||||
jobs:
|
|
||||||
fuzz:
|
|
||||||
runs-on: heavy
|
|
||||||
timeout-minutes: 90
|
|
||||||
steps:
|
|
||||||
- uses: actions/checkout@v4
|
|
||||||
with:
|
|
||||||
submodules: recursive
|
|
||||||
|
|
||||||
# pixi: the image's when it is the pinned version, else the pinned release, fetched into a cache directory
|
|
||||||
# (which lasts only where the runner keeps a home between jobs) and checked by SHA-256
|
|
||||||
- name: pixi, pinned
|
|
||||||
shell: bash
|
|
||||||
run: |
|
|
||||||
set -euo pipefail
|
|
||||||
if command -v pixi >/dev/null && [ "$(pixi --version | cut -d' ' -f2)" = "$PIXI_VERSION" ]; then
|
|
||||||
echo "pixi $PIXI_VERSION is on the PATH: $(command -v pixi)"; exit 0
|
|
||||||
fi
|
|
||||||
dir="${PPLUS_CI_CACHE:-$HOME/.cache/pplus-ci}/pixi-$PIXI_VERSION"
|
|
||||||
if [ ! -x "$dir/pixi" ]; then
|
|
||||||
case "$(uname -s)-$(uname -m)" in
|
|
||||||
Linux-x86_64) asset=pixi-x86_64-unknown-linux-musl.tar.gz; sum=064f371e692aaa3400ac581c89da2843c91437f20c2d9155395a5d0037f33551 ;;
|
|
||||||
Linux-aarch64) asset=pixi-aarch64-unknown-linux-musl.tar.gz; sum=d08403d8f048626ec93ba7b7c56e3b747a5f3a95c4e6e0c815ceb264f5f0b9ce ;;
|
|
||||||
*) echo "no pinned pixi for $(uname -sm)" >&2; exit 1 ;;
|
|
||||||
esac
|
|
||||||
tmp="$(mktemp -d)"
|
|
||||||
curl -fsSL --retry 3 -o "$tmp/$asset" "https://github.com/prefix-dev/pixi/releases/download/v$PIXI_VERSION/$asset"
|
|
||||||
echo "$sum $tmp/$asset" | sha256sum -c -
|
|
||||||
mkdir -p "$dir" && tar -xzf "$tmp/$asset" -C "$dir" pixi && rm -rf "$tmp"
|
|
||||||
fi
|
|
||||||
echo "$dir" >> "$GITHUB_PATH"
|
|
||||||
"$dir/pixi" --version
|
|
||||||
|
|
||||||
- name: The pinned environment, exactly as pixi.lock has it
|
|
||||||
run: pixi install --locked
|
|
||||||
|
|
||||||
# mojo-status-strict, then mojo-fuzz in both modes (four seeds, 100 programs each) and prove-fuzz (four seeds, 3,000 each);
|
|
||||||
# every seed is printed with the command that reproduces it
|
|
||||||
- name: pixi run nightly
|
|
||||||
run: pixi run nightly
|
|
||||||
+14
-77
@@ -1,88 +1,25 @@
|
|||||||
# pplus-core's gate on every push and pull request: `pixi run ci`, the same task a developer runs, in the
|
# pplus-core on Gitea Actions, with a runner that has no container image: the act_runner runs jobs directly on the
|
||||||
# environment pixi.lock pins (Node, Python, the Mojo compiler), so CI and a developer cannot drift. docs/ci.md says
|
# host's shell ("host mode"; pplus-web's docs/deploy.md has the runner setup). Every push and pull request builds
|
||||||
# what it runs, how long it takes, and what to do when it fails.
|
# and tests core, and checks that every Mojo program of ours still passes, offline, from godbolt's stored answers.
|
||||||
#
|
|
||||||
# Gitea Actions, on the runner with the label `heavy`: a machine with cores to spare, not the server that deploys
|
|
||||||
# the site, because the gate builds and runs some 300 Mojo programs and fuzzes (docs/ci.md has the runner's setup).
|
|
||||||
# With no such runner registered a run waits; nothing here runs on the deploy server. What the job needs beyond git,
|
|
||||||
# Node and curl comes from pixi.lock or is fetched by a pinned hash, so the runner may be a container or a host.
|
|
||||||
# The same file runs on GitHub Actions with one change: `runs-on: ubuntu-latest`.
|
|
||||||
name: Test
|
name: Test
|
||||||
on:
|
on:
|
||||||
push:
|
push:
|
||||||
pull_request:
|
pull_request:
|
||||||
workflow_dispatch:
|
workflow_dispatch:
|
||||||
|
|
||||||
concurrency:
|
|
||||||
group: test-${{ github.ref }}
|
|
||||||
cancel-in-progress: true
|
|
||||||
|
|
||||||
env:
|
|
||||||
# set by Gitea and GitHub Actions already; written here so the tests' "fail, not skip, under CI" never depends on it
|
|
||||||
CI: "true"
|
|
||||||
# the pixi that reads pixi.lock; when the runner has another version, this one is fetched into the cache below
|
|
||||||
PIXI_VERSION: "0.83.0"
|
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
gate:
|
test:
|
||||||
# a pull request runs only from a branch of this repository: a fork's workflow would run its own code on the
|
runs-on: quarto-deploy
|
||||||
# runner (docs/ci.md). Drop this line for a runner that is a throwaway machine.
|
|
||||||
if: github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository
|
|
||||||
runs-on: heavy
|
|
||||||
timeout-minutes: 60
|
|
||||||
steps:
|
steps:
|
||||||
# library/ is pplus-library, a submodule pinned by commit: the programs, the corpus, the routines
|
|
||||||
- uses: actions/checkout@v4
|
- uses: actions/checkout@v4
|
||||||
with:
|
- name: Toolchain on the host
|
||||||
submodules: recursive
|
|
||||||
|
|
||||||
# pixi: the image's when it is the pinned version, else the pinned release, fetched into a cache directory
|
|
||||||
# (which lasts only where the runner keeps a home between jobs) and checked by SHA-256
|
|
||||||
- name: pixi, pinned
|
|
||||||
shell: bash
|
|
||||||
run: |
|
run: |
|
||||||
set -euo pipefail
|
node --version
|
||||||
if command -v pixi >/dev/null && [ "$(pixi --version | cut -d' ' -f2)" = "$PIXI_VERSION" ]; then
|
npm --version
|
||||||
echo "pixi $PIXI_VERSION is on the PATH: $(command -v pixi)"; exit 0
|
python3 --version || echo "python3 missing: the pipelines' tests are skipped"
|
||||||
fi
|
- run: npm ci
|
||||||
dir="${PPLUS_CI_CACHE:-$HOME/.cache/pplus-ci}/pixi-$PIXI_VERSION"
|
- run: npm test
|
||||||
if [ ! -x "$dir/pixi" ]; then
|
- name: Our Mojo programs pass
|
||||||
case "$(uname -s)-$(uname -m)" in
|
|
||||||
Linux-x86_64) asset=pixi-x86_64-unknown-linux-musl.tar.gz; sum=064f371e692aaa3400ac581c89da2843c91437f20c2d9155395a5d0037f33551 ;;
|
|
||||||
Linux-aarch64) asset=pixi-aarch64-unknown-linux-musl.tar.gz; sum=d08403d8f048626ec93ba7b7c56e3b747a5f3a95c4e6e0c815ceb264f5f0b9ce ;;
|
|
||||||
*) echo "no pinned pixi for $(uname -sm)" >&2; exit 1 ;;
|
|
||||||
esac
|
|
||||||
tmp="$(mktemp -d)"
|
|
||||||
curl -fsSL --retry 3 -o "$tmp/$asset" "https://github.com/prefix-dev/pixi/releases/download/v$PIXI_VERSION/$asset"
|
|
||||||
echo "$sum $tmp/$asset" | sha256sum -c -
|
|
||||||
mkdir -p "$dir" && tar -xzf "$tmp/$asset" -C "$dir" pixi && rm -rf "$tmp"
|
|
||||||
fi
|
|
||||||
echo "$dir" >> "$GITHUB_PATH"
|
|
||||||
"$dir/pixi" --version
|
|
||||||
|
|
||||||
- name: The pinned environment, exactly as pixi.lock has it
|
|
||||||
run: pixi install --locked
|
|
||||||
|
|
||||||
# .tools/ holds the pinned Dafny and mojo-local's answers (keyed by compiler, arguments and source); it is a
|
|
||||||
# link into the cache directory, so where the runner keeps a home between jobs neither is fetched or built again
|
|
||||||
- name: The pinned Dafny
|
|
||||||
shell: bash
|
|
||||||
run: |
|
run: |
|
||||||
set -euo pipefail
|
if command -v python3 >/dev/null; then python3 scripts/mojo/corpus.py status --strict
|
||||||
cache="${PPLUS_CI_CACHE:-$HOME/.cache/pplus-ci}/core-tools"
|
else echo "python3 missing: corpus status skipped"; fi
|
||||||
mkdir -p "$cache"
|
|
||||||
if [ -d .tools ] && [ ! -L .tools ]; then echo ".tools is a directory in this checkout already: using it"; else ln -sfn "$cache" .tools; fi
|
|
||||||
pixi run dafny-fetch
|
|
||||||
|
|
||||||
# every test, mojo-status-strict, library-check, mojo-local and a short mojo-fuzz and prove-fuzz (pixi.toml)
|
|
||||||
- name: pixi run ci
|
|
||||||
run: pixi run ci
|
|
||||||
|
|
||||||
# the gate rewrites what it records (the library's status.json and STATUS.md, the corpus's STATUS.md); a
|
|
||||||
# difference means a change was committed without what it regenerates
|
|
||||||
- name: Nothing the gate regenerates differs from what is committed
|
|
||||||
shell: bash
|
|
||||||
run: |
|
|
||||||
set -euo pipefail
|
|
||||||
git diff --stat --exit-code
|
|
||||||
git -C library diff --stat --exit-code
|
|
||||||
+2
-2
@@ -3,8 +3,8 @@ dist/
|
|||||||
.DS_Store
|
.DS_Store
|
||||||
patches/
|
patches/
|
||||||
package/
|
package/
|
||||||
# the pinned Dafny (pixi run dafny-fetch, scripts/dafny.py) and mojo-local's answers; in CI a link to a cache
|
# the pinned Dafny, fetched by `pixi run dafny-fetch` (scripts/dafny.py)
|
||||||
.tools
|
.tools/
|
||||||
# pixi environments
|
# pixi environments
|
||||||
.pixi/*
|
.pixi/*
|
||||||
!.pixi/config.toml
|
!.pixi/config.toml
|
||||||
|
|||||||
@@ -1,4 +0,0 @@
|
|||||||
[submodule "library"]
|
|
||||||
path = library
|
|
||||||
url = https://git.scient.ing/pplus/pplus-library.git
|
|
||||||
branch = main
|
|
||||||
@@ -1,36 +1,35 @@
|
|||||||
# AGENTS.md
|
# AGENTS.md
|
||||||
|
|
||||||
Instructions for coding agents (and people) changing pplus-core. Programming+ takes a procedure from an idea to Mojo to the machine. Core decides what a program means in each of its notations: lingo (steps in plain English), matho (equations written in LaTeX), pseudo (pseudocode precise enough to run, prove and translate), speco (a specification to prove against) and Mojo (Modular's programming language, pinned to version 1.2.0). Read this first, then the [README](README.md) for what core is and where things are. When this file and a task's instructions disagree, the task wins; say so in your summary.
|
Instructions for coding agents (and people) changing pplus-core. Read this first, then the [README](README.md) for what core 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
|
## Build, test, and the gate
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
pixi run test # build, then every test (node --test against dist/, the pipelines' Python tests included)
|
pixi run test # build, then every test (node --test against dist/, the pipelines' Python tests included)
|
||||||
pixi run ci # what CI runs: every test, no Mojo program we wrote failing by godbolt's stored answers, library-check, mojo-local, a short fuzz (docs/ci.md)
|
pixi run ci # the gate: every test, and no Mojo program of ours failing
|
||||||
```
|
```
|
||||||
|
|
||||||
Without pixi (a sandbox with only Node and Python):
|
Without pixi (a sandbox with only Node and Python):
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
npx tsc -p tsconfig.json && node --test --test-concurrency=8 tests/*.test.mjs
|
npx tsc -p tsconfig.json && node --test tests/*.test.mjs
|
||||||
python3 scripts/mojo/corpus.py status --strict
|
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.
|
**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 under a minute (25 s on the machine this was last measured on). It runs eight files at a time: Node's default is one fewer than the processor count, and on a 24-core machine the 41 files at once (each 60 to 490 MB at its peak) passed a 3 GB memory cap on some runs and were OOM-killed on others; eight at a time peaked at 1.9 GB in the same 22 s. While iterating, build and run one file: `npx tsc -p tsconfig.json && node --test tests/sync-hub.test.mjs`.
|
The full suite takes about two minutes. While iterating, build and run one file: `npx tsc -p tsconfig.json && node --test tests/sync-hub.test.mjs`.
|
||||||
|
|
||||||
## Hard rules
|
## Hard rules
|
||||||
|
|
||||||
1. **Core has no DOM.** What a program means is decided without a browser. A library module never touches `document`, `window`, `localStorage` or `navigator`, never imports one of a course's page widgets, and never imports from outside `src/`; `tests/boundary.test.mjs` holds it to that. The widgets (listed in that test) live beside the engines only so a course's site and pplus-web take them from one place.
|
1. **Core has no DOM.** What a program means is decided without a browser. A library module never touches `document`, `window`, `localStorage` or `navigator`, never imports one of the course's page widgets, and never imports from outside `src/`; `tests/boundary.test.mjs` holds it to that. The widgets (listed in that test) live beside the engines only so the course and pplus-web take them from one place.
|
||||||
2. **Do not edit generated files by hand.** `src/mojo/generated/*` and `library/syntax/mojo.xml` come from the corpus pipeline (`pixi run mojo-emit`, `mojo-status`, `play`). `src/library/generated.ts` comes from `library/` (`pixi run library-emit`), and the library's `status.json`, `STATUS.md` and `golden/` from `pixi run library-check` and `library-verify-mojo`. `library/mojo/corpus/` comes from `mojo-harvest`. `library/mojo/golden/` holds godbolt's answers and comes only from `mojo-verify`.
|
2. **Do not edit generated files by hand.** `src/mojo/generated/*` and `syntax/mojo.xml` come from the corpus pipeline (`pixi run mojo-emit`, `mojo-status`, `play`). `mojo/corpus/` comes from `mojo-harvest`. `mojo/golden/` holds godbolt's answers and comes only from `mojo-verify`.
|
||||||
3. **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. **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>'`.
|
||||||
4. **Never claim Mojo compiles, runs, or prints something without the real compiler's answer.** Mojo is pinned to 1.2.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 from godbolt's stored answers, and `pixi run mojo-local` and `pixi run mojo-fuzz` hold them, and the Mojo the translator writes, to the pinned compiler on your machine. Run `mojo-local` after any change to `src/mojo/` or `src/sync/pseudo-to-mojo.ts`. Every Mojo construct you write into core must pass `checkMojo`, and every standard-library name must exist in `src/mojo/generated/stdlib.ts` or `types.ts`.
|
4. **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 core must pass `checkMojo`, and every standard-library name must exist in `src/mojo/generated/stdlib.ts` or `types.ts`.
|
||||||
5. **Never let the prover call something proved that a run breaks.** "Proved" must be a proof. A change to `src/engines/pseudo/logic.ts`, `solver.ts` or `vcgen.ts` keeps `tests/prover-soundness.test.mjs` and `tests/engine-solver.test.mjs` green, and a fact the prover assumes must hold for every value a run can produce, or be guarded by an obligation. When you find a soundness bug, add the program that shows it to `library/pseudo/prover/` with a `// MUST-NOT-PROVE:` (or `// RUN-STOPS:`) header first, see the test fail, then fix the rule ([docs/engines.md](docs/engines.md#soundness)).
|
5. **Never let the prover call something proved that a run breaks.** "Proved" must be a proof. A change to `src/engines/pseudo/logic.ts`, `solver.ts` or `vcgen.ts` keeps `tests/prover-soundness.test.mjs` and `tests/engine-solver.test.mjs` green, and a fact the prover assumes must hold for every value a run can produce, or be guarded by an obligation. When you find a soundness bug, add the program that shows it to `tests/prover/` with a `// MUST-NOT-PROVE:` (or `// RUN-STOPS:`) header first, see the test fail, then fix the rule ([docs/engines.md](docs/engines.md#soundness)).
|
||||||
6. **No new dependencies.** TypeScript is the only npm package; there is no runtime dependency. The pipelines (the Mojo corpus, the Dafny pin) are Python's standard library only. Tools that are not npm packages are pinned: Mojo, Node and Python by pixi, Dafny by `scripts/dafny.py` (a version and a SHA-256 per platform).
|
6. **No new dependencies.** TypeScript is the only npm package; there is no runtime dependency. The pipelines (the Mojo corpus, the Dafny pin) are Python's standard library only. Tools that are not npm packages are pinned: Mojo, Node and Python by pixi, Dafny by `scripts/dafny.py` (a version and a SHA-256 per platform).
|
||||||
7. **You have no network** in most sandboxes. Godbolt (`mojo-verify`), GitHub (`mojo-harvest`, `mojo-fetch`, `dafny-fetch`) need one. Never fake their results; leave those steps to the owner and list them.
|
7. **You have no network** in most sandboxes. Godbolt (`mojo-verify`), GitHub (`mojo-harvest`, `mojo-fetch`, `dafny-fetch`) need one. Never fake their results; leave those steps to the owner and list them.
|
||||||
8. **Core's exports are pplus-web's API.** pplus-web imports core's built modules as `#core/<path>` and builds against the declarations in `dist/`. Renaming or removing an export, or changing what a function returns, breaks the site; when you do it, say so in the summary so web is updated in the same release.
|
8. **Core's exports are pplus-web's API.** pplus-web imports core's built modules as `#core/<path>` and builds against the declarations in `dist/`. Renaming or removing an export, or changing what a function returns, breaks the site; when you do it, say so in the summary so web is updated in the same release.
|
||||||
9. **Data lives in pplus-library, code lives here.** Programs, corpora, pins, fixtures and stored answers belong in `library/` (its own AGENTS.md has its rules); scripts, engines and tests that read them stay in core. A change under `library/` is committed and pushed in pplus-library first, then committed here with the new submodule pointer (`git add library`) and whatever core regenerated from it.
|
|
||||||
|
|
||||||
## Conventions
|
## Conventions
|
||||||
|
|
||||||
@@ -48,9 +47,8 @@ The full suite takes under a minute (25 s on the machine this was last measured
|
|||||||
| 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 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>"` |
|
| 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 |
|
| 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 `library/pseudo/programs/` whose `// EXPECT:` lines are the output it must print |
|
| A pseudo regression program | a file in `tests/corpus/` whose `// EXPECT:` lines are the output it must print |
|
||||||
| A prover soundness regression | a file in `library/pseudo/prover/` whose `// MUST-NOT-PROVE: <kind>@<line>` names an obligation a run breaks, or `// RUN-STOPS: <kind>@<line>` where a run must stop |
|
| A prover soundness regression | a file in `tests/prover/` whose `// MUST-NOT-PROVE: <kind>@<line>` names an obligation a run breaks, or `// RUN-STOPS: <kind>@<line>` where a run must stop |
|
||||||
| A verified routine others can USE | in pplus-library (`library/`), under its AGENTS.md; then `pixi run library-check` and `library-emit` here ([docs/library.md](docs/library.md)) |
|
|
||||||
| A command | a task in `pixi.toml` and a row in the README's Commands table |
|
| A command | a task in `pixi.toml` and a row in the README's Commands table |
|
||||||
| A language | a `LanguageService` (`src/common/types.ts`) in `src/services/`, registered in `src/services/index.ts` |
|
| A language | a `LanguageService` (`src/common/types.ts`) in `src/services/`, registered in `src/services/index.ts` |
|
||||||
|
|
||||||
|
|||||||
@@ -1,74 +0,0 @@
|
|||||||
# Changelog
|
|
||||||
|
|
||||||
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
|
||||||
No version has been tagged yet. The library, pplus-library, is pinned by commit and has a changelog of its own.
|
|
||||||
|
|
||||||
## [Unreleased]
|
|
||||||
|
|
||||||
Mojo 1.2.0, held to the real compiler on the machine as well as on godbolt.org, and the fixes three audits found.
|
|
||||||
|
|
||||||
### Changed
|
|
||||||
|
|
||||||
- Everything Mojo is pinned to Mojo 1.2.0 (it was 1.1.0): the pin, the harvested corpus, godbolt's answers for every program, and the words the checker and the editor know. The corpus pipeline reads a release's notes from the nightly changelog when the tag has none, and `pixi run mojo-prune` removes stored answers nothing reads.
|
|
||||||
- `pixi run library-check` builds and runs every Mojo reference and the Mojo generated from each routine on the pinned compiler on the machine; every Mojo reference has the compiler's stored answer.
|
|
||||||
- The pseudo parser, checker and interpreter (`lang`, `numeric`, `parse`, `check`, `interp`) are strict TypeScript on a typed syntax tree (`ast.ts`), with no change in behavior: 0 differences over 8,451 texts against the JavaScript they replace.
|
|
||||||
- A routine's compiled references read their cases at run time; three checks that had agreed only because the compiler worked the answer out while building are now real.
|
|
||||||
- New limits, each a located diagnostic or a named stop and all listed in `docs/limits.md`: how deep and how long a Mojo, lingo, matho or pseudo text may be, how large a value a Mojo run may make, how much work the prover and the generated tests may do, and how much memory an x86-64 setup may name.
|
|
||||||
- The sources are in US English: `normalizeAnswer` (was `normaliseAnswer`), the lesson and concept id `memoization`, "not modeled" in messages.
|
|
||||||
- Mojo is built one stated way everywhere core builds it or asks godbolt to (the Compile button, the corpus, the library's references, `mojo-local`, `mojo-fuzz`, `mojo-run`): the arguments are `build.args` in the library's pin, before a program's own. `--target-cpu x86-64-v3` makes a listing the same whichever of godbolt's machines answers (one answered with AVX-512, which the model machine does not know); `--fp-mode contract=off` rounds every Float64 operation on its own, as both interpreters do, where Mojo's default fuses a multiply with an add. `BUILD_ARGS` carries them and `BUILD_LEVELS` is new. `mojo build` with no arguments targets the machine it runs on and may fuse (`docs/trust.md`).
|
|
||||||
- The Mojo syntax definition the pipeline writes states its license as Apache-2.0 (it said MIT), and `THIRD_PARTY.md` says that the engines and the lessons, which came from the course, are under this repository's copyright and license.
|
|
||||||
|
|
||||||
- `pixi run cli prove` has no time limit unless `--budget-ms` gives one, and `library-check` proves without one: their answers are the prover's counted budgets' alone, the same on every machine. The clock is the caller's (`provePseudo(parsed, { budgetMs })`, `Workspace.proofBudgetMs`); left out, it is the Prove tab's 3 seconds (`PROVE_BUDGET_MS`), as before.
|
|
||||||
- The pinned environment has a C compiler on Linux (`gcc` from conda-forge, with the C library it links against pinned to glibc 2.34, which Mojo's runtime needs): `mojo build` links with the C compiler it finds, so until now a build depended on the system's, and on a machine without one (CI's image) no Mojo program could be built. The C references and the C harness are built with it too. `mojo-local` reports a program that could not be linked as that, not as rejected by the compiler, and does not keep the answer.
|
|
||||||
|
|
||||||
### Added
|
|
||||||
|
|
||||||
- A proof report says when the time on the clock, not the proof, stopped a routine: `ProofReport.clock` has the budget and the routines it stopped, each such unit has `timedOut` and a note, and `checkProperties` answers `timedOut` when the clock cut its inputs short. Inputs cut short count only where a claim of the routine is still open: on a routine whose every claim is proved nothing was left undecided. The site uses it to offer more time.
|
|
||||||
- `pixi run mojo-local` builds every Mojo program core holds or generates on the pinned local compiler and holds the checker, the interpreter and the translator to it; `pixi run mojo-fuzz` does the same with generated programs.
|
|
||||||
- `pixi run mojo-fuzz --statements` generates whole programs (loops, branches, collections, records, routines with BYREF), builds each with the pinned compiler and holds its output to the pseudo's line by line; `pixi run prove-fuzz` holds the prover to runs of generated programs. `pixi run ci` runs both on a fixed and a moving seed, and `pixi run nightly` runs them longer.
|
|
||||||
- The Mojo interpreter runs what the translator writes: typed list literals, `List[T](slice)`, `ord` and `chr`, std.math's exact functions (`gcd`, `lcm`, `comb`, `hypot`, `fma`, `nextafter`, `ulp`, `copysign`, `isinf` and the others), `atof` of a decimal, and the `match` statement. What it declines on purpose (a fractional power, the transcendental functions, random numbers) says why.
|
|
||||||
- CI workflows that run the gate a developer runs (`pixi run ci`: every test, strict corpus status, library-check, mojo-local and a short fuzz), and a scheduled one for the longer fuzz.
|
|
||||||
- `docs/limits.md`, `docs/ci.md`, and a test that holds the sources, scripts and tests to US English.
|
|
||||||
- Third-party inventories: `THIRD_PARTY.md` here and the library's, written from the pin, the lock and every harvested file, and tests that fail when they fall behind.
|
|
||||||
- The Apache License 2.0, a NOTICE, contributing rules, a security policy, a code of conduct, and a citation file.
|
|
||||||
|
|
||||||
### Fixed
|
|
||||||
|
|
||||||
- The gate no longer depends on the machine it runs on. It first ran on the server that deploys the site, a slow container image without a C compiler or ICU, where ten tests failed on correct code and no Mojo program could be built. The pinned Dafny starts without ICU (it is run with `DOTNET_SYSTEM_GLOBALIZATION_INVARIANT=1`), and `dafny-fetch` fails when the Dafny it fetched does not start (it printed an empty version and went on). A test's time limit is processor time at the machine's pace (`tests/helpers/pace.mjs`), and the tests that hold what the prover proves give it no time on the clock.
|
|
||||||
- The workflows run on a runner with the label `heavy`, not on the deploy server: the gate builds and runs some 300 Mojo programs. `docs/ci.md` says how to register one, and describes the runners as they are (the workflows' comments described a host-mode runner that was never what ran them).
|
|
||||||
- The translator writes Mojo the compiler accepts and that prints what the pseudo prints.
|
|
||||||
- The Mojo interpreter: a numeric literal beside a Float32 is a Float32; a float to a whole power is computed as the compiler computes it, and to any other power the interpreter declines; a list in brackets takes a List's element type.
|
|
||||||
- The prover: 18 rules that proved what a run breaks are closed, each with a regression program in the library.
|
|
||||||
- Pseudo: wrong answers (MOD past 2^53, CHOOSE, sums over whole numbers, literals past 2^53, sized types leaving their type, FLOAT32 literals rounded twice, comparisons with USE IEEE), crashes on malformed input, and missing limits (quantifier bodies and the Prove tab's fuzzing now have one), from an audit against exact arithmetic.
|
|
||||||
- Pseudo: a FUNCTION called inside an IF, WHILE or UNTIL condition ran twice, because the step's explanation evaluated it again; a second routine of a name was checked with the first one's record, and one named after a built-in could make the checker throw.
|
|
||||||
- The translator, from the statement fuzzer: about twenty-five shapes the compiler rejected or that printed something else (two names that become one, a name declared in a block and used after it, a variable some path leaves unset, DELETE on a set, slices, constants' types, CONTINUE in a REPEAT, an argument evaluated once per pass of a loop). Each is pinned in `tests/sync-mojo.test.mjs`.
|
|
||||||
- A function sent from a compiled listing to the x86-64 pane brought its read-only data as `bytes 0x.. 0x..`, five characters a byte: with the compiler's half-megabyte table of source locations the setup was 2.5 MB, more than a share link may hold. A long block is quoted text with `\xHH` escapes, which the setup reads back to the same bytes; a `#`, `;` or `//` inside quoted text is text.
|
|
||||||
- No text makes a reader or a run end in the engine's own error: 20 nested `ABS` no longer take the prover's memory, 30,000 nested brackets are one diagnostic, and anything a reader still throws becomes `engine-stop` on its pane.
|
|
||||||
- `scripts/mojo/listings.mjs` (run by `pixi run play`) wrote every function of a program into its exercise's x86-64 pane, not the one the exercise is about and what it calls as `docs/mojo-corpus.md` says: for `demo` 8,634 lines and a 2.9 MB `listings.ts`, with which the test suite passed a 3 GB memory cap. It writes the entry and its callees again, the stored listing's `build` is the arguments its answer was asked with (the pin's first), and a test fails when `listings.ts` is not what the tool writes or grows past 64 kB.
|
|
||||||
- A FLOAT made into a whole number must be one the lab holds exactly.
|
|
||||||
- What core said about fused multiply-adds: with its default `--fp-mode contract=fast`, Mojo 1.2.0 fuses a multiply with an add where the operands arrive at run time; core now builds with contraction off, and three library references that needed a tolerance for it agree exactly again.
|
|
||||||
- `pixi run mojo-local` compares a program given stdin with godbolt's stored answer too: godbolt does deliver stdin.
|
|
||||||
- Pseudo: brackets that each hold a long chain (three levels of 399 values, inside both the 200-level and the 400-value limit) built a tree about 1,200 levels tall, and the checker ended in the engine's own stack error. An expression's tree is now held to 400 levels where it is complete (`MAX_TREE`), one `too-deep` error.
|
|
||||||
- `docs/engines.md` is corrected against the code (which modules are TypeScript, which built-ins carry an `argument` obligation, what the reference test runs, what this repository changed in the engines), and the reference says the prover has 3 seconds for each routine, not for the program.
|
|
||||||
|
|
||||||
## [0.2.0] - 2026-10-06
|
|
||||||
|
|
||||||
The engines' first home of their own, as `main` holds it. Never tagged.
|
|
||||||
|
|
||||||
### Added
|
|
||||||
|
|
||||||
- pplus-core as a project of its own: the languages, translators, Mojo checker and interpreter, prover, fuzzer and x86-64 machine model, with no DOM, used by pplus-web and the course as a pinned dependency. This repository owns the engines, and `pixi run engines-export` gives them to the course.
|
|
||||||
- A `Workspace` for one piece of work and what its sources mean; Compile & run goes through a `CompileBackend`; `docs/trust.md` says what each verdict means.
|
|
||||||
- Pseudo for numerical work: sized types (INT8 to UINT64, FLOAT32), exact built-ins, `USE IEEE`.
|
|
||||||
- `USE` and pplus-library as the submodule `library/`: routines verified once and used by name. The Mojo corpus and its stored answers moved into the library.
|
|
||||||
|
|
||||||
### Changed
|
|
||||||
|
|
||||||
- The prover's term language, solver and verification-condition generator are TypeScript, each with tests of its own.
|
|
||||||
|
|
||||||
### Fixed
|
|
||||||
|
|
||||||
- The prover is sound for what its gate holds: two rules fixed, missing obligations added, a soundness test over regression programs.
|
|
||||||
- A run stops on a FLOAT that is not finite, so proofs about FLOAT hold.
|
|
||||||
- "X is in the collection" is known inside a FOR EACH pass, not on the way out.
|
|
||||||
- A call's result prints in its own type: a FLOAT result 3.0 is not shown as 3.
|
|
||||||
@@ -1,21 +0,0 @@
|
|||||||
cff-version: 1.2.0
|
|
||||||
message: "If you use Programming+ in published work, please cite it as below."
|
|
||||||
type: software
|
|
||||||
title: "pplus-core: the languages, translators, Mojo checker and interpreter, prover and machine model of Programming+"
|
|
||||||
version: 0.2.0
|
|
||||||
authors:
|
|
||||||
- family-names: Maldonado
|
|
||||||
given-names: Alex M.
|
|
||||||
email: alex@scient.ing
|
|
||||||
orcid: "https://orcid.org/0000-0003-3280-062X"
|
|
||||||
- name: Scientific Computing Studio, LLC
|
|
||||||
email: us@scient.ing
|
|
||||||
url: "https://pplus.scient.ing"
|
|
||||||
repository-code: "https://git.scient.ing/pplus/pplus-core"
|
|
||||||
license: Apache-2.0
|
|
||||||
keywords:
|
|
||||||
- programming education
|
|
||||||
- pseudocode
|
|
||||||
- Mojo
|
|
||||||
- program verification
|
|
||||||
- computer architecture
|
|
||||||
@@ -1,84 +0,0 @@
|
|||||||
# Contributor Covenant Code of Conduct
|
|
||||||
|
|
||||||
## Our Pledge
|
|
||||||
|
|
||||||
We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, caste, color, religion, or sexual identity and orientation.
|
|
||||||
|
|
||||||
We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community.
|
|
||||||
|
|
||||||
## Our Standards
|
|
||||||
|
|
||||||
Examples of behavior that contributes to a positive environment for our community include:
|
|
||||||
|
|
||||||
* Demonstrating empathy and kindness toward other people
|
|
||||||
* Being respectful of differing opinions, viewpoints, and experiences
|
|
||||||
* Giving and gracefully accepting constructive feedback
|
|
||||||
* Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience
|
|
||||||
* Focusing on what is best not just for us as individuals, but for the overall community
|
|
||||||
|
|
||||||
Examples of unacceptable behavior include:
|
|
||||||
|
|
||||||
* The use of sexualized language or imagery, and sexual attention or advances of any kind
|
|
||||||
* Trolling, insulting or derogatory comments, and personal or political attacks
|
|
||||||
* Public or private harassment
|
|
||||||
* Publishing others' private information, such as a physical or email address, without their explicit permission
|
|
||||||
* Other conduct which could reasonably be considered inappropriate in a professional setting
|
|
||||||
|
|
||||||
## Enforcement Responsibilities
|
|
||||||
|
|
||||||
Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful.
|
|
||||||
|
|
||||||
Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate.
|
|
||||||
|
|
||||||
## Scope
|
|
||||||
|
|
||||||
This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event.
|
|
||||||
|
|
||||||
## Enforcement
|
|
||||||
|
|
||||||
Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at alex@scient.ing. All complaints will be reviewed and investigated promptly and fairly.
|
|
||||||
|
|
||||||
All community leaders are obligated to respect the privacy and security of the reporter of any incident.
|
|
||||||
|
|
||||||
## Enforcement Guidelines
|
|
||||||
|
|
||||||
Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct:
|
|
||||||
|
|
||||||
### 1. Correction
|
|
||||||
|
|
||||||
**Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community.
|
|
||||||
|
|
||||||
**Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested.
|
|
||||||
|
|
||||||
### 2. Warning
|
|
||||||
|
|
||||||
**Community Impact**: A violation through a single incident or series of actions.
|
|
||||||
|
|
||||||
**Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban.
|
|
||||||
|
|
||||||
### 3. Temporary Ban
|
|
||||||
|
|
||||||
**Community Impact**: A serious violation of community standards, including sustained inappropriate behavior.
|
|
||||||
|
|
||||||
**Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban.
|
|
||||||
|
|
||||||
### 4. Permanent Ban
|
|
||||||
|
|
||||||
**Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals.
|
|
||||||
|
|
||||||
**Consequence**: A permanent ban from any sort of public interaction within the community.
|
|
||||||
|
|
||||||
## Attribution
|
|
||||||
|
|
||||||
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.1, available at [https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1].
|
|
||||||
|
|
||||||
Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder][Mozilla CoC].
|
|
||||||
|
|
||||||
For answers to common questions about this code of conduct, see the FAQ at [https://www.contributor-covenant.org/faq][FAQ]. Translations are available at [https://www.contributor-covenant.org/translations][translations].
|
|
||||||
|
|
||||||
[homepage]: https://www.contributor-covenant.org
|
|
||||||
[v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html
|
|
||||||
[Mozilla CoC]: https://github.com/mozilla/diversity
|
|
||||||
[FAQ]: https://www.contributor-covenant.org/faq
|
|
||||||
[translations]: https://www.contributor-covenant.org/translations
|
|
||||||
|
|
||||||
@@ -1,35 +0,0 @@
|
|||||||
# Contributing
|
|
||||||
|
|
||||||
Thank you for reading this far.
|
|
||||||
pplus-core is the part of Programming+ that has to be right, and it is maintained by one person; the rules below keep it honest about what it can take on.
|
|
||||||
|
|
||||||
## Two rules first
|
|
||||||
|
|
||||||
- **No outside code is merged until a contributor license agreement exists.** Until then, bug reports, failing programs, questions, and documentation fixes are welcome, and code changes are read and used as guidance but not merged. The agreement will be short and will ask you to confirm that you may license your change under Apache-2.0.
|
|
||||||
- **No contributions from students enrolled at the University of Pittsburgh.** The maintainer teaches there, and this project is separate from that job. Students may use Programming+ like anyone else.
|
|
||||||
|
|
||||||
## Running the checks
|
|
||||||
|
|
||||||
Programming+ uses [pixi](https://pixi.sh/latest/) for its environments; it brings the pinned Mojo, Node and Python.
|
|
||||||
From a clone with its submodule (`git clone --recurse-submodules`):
|
|
||||||
|
|
||||||
```sh
|
|
||||||
pixi run test # build, then every test
|
|
||||||
pixi run ci # the gate: every test, no Mojo program of ours failing, every library routine checked,
|
|
||||||
# every program built by the pinned compiler, and a short fuzz (docs/ci.md)
|
|
||||||
```
|
|
||||||
|
|
||||||
Without pixi, with Node 20 or later: `npm install && npm test`.
|
|
||||||
[AGENTS.md](AGENTS.md) has the rules every change follows, whoever writes it: the gate, the generated files nobody edits by hand, and why a claim about Mojo needs the real compiler's answer.
|
|
||||||
|
|
||||||
## Reporting a bug
|
|
||||||
|
|
||||||
Say what you ran, what you expected, and what happened.
|
|
||||||
The best report is a program: a pseudo program and the output it should print, a Mojo program and what the compiler says about it, or a program the prover calls proved that a run breaks (that one is a soundness bug, the most serious kind; [docs/engines.md](docs/engines.md#soundness) says how they are pinned).
|
|
||||||
Where to file issues will be in the README once the repository is public.
|
|
||||||
|
|
||||||
## Style
|
|
||||||
|
|
||||||
US English, plain sentences.
|
|
||||||
A commit says the problem first, then what each part of the change does, and a fix comes with a test that fails without it.
|
|
||||||
Every change for a user has a line in `CHANGELOG.md`.
|
|
||||||
-167
@@ -1,167 +0,0 @@
|
|||||||
# Apache License
|
|
||||||
|
|
||||||
_Version 2.0, January 2004_
|
|
||||||
_<<http://www.apache.org/licenses/>>_
|
|
||||||
|
|
||||||
## Terms and Conditions for use, reproduction, and distribution
|
|
||||||
|
|
||||||
### 1. Definitions
|
|
||||||
|
|
||||||
“License” shall mean the terms and conditions for use, reproduction, and
|
|
||||||
distribution as defined by Sections 1 through 9 of this document.
|
|
||||||
|
|
||||||
“Licensor” shall mean the copyright owner or entity authorized by the copyright
|
|
||||||
owner that is granting the License.
|
|
||||||
|
|
||||||
“Legal Entity” shall mean the union of the acting entity and all other entities
|
|
||||||
that control, are controlled by, or are under common control with that entity.
|
|
||||||
For the purposes of this definition, “control” means **(i)** the power, direct or
|
|
||||||
indirect, to cause the direction or management of such entity, whether by
|
|
||||||
contract or otherwise, or **(ii)** ownership of fifty percent (50%) or more of the
|
|
||||||
outstanding shares, or **(iii)** beneficial ownership of such entity.
|
|
||||||
|
|
||||||
“You” (or “Your”) shall mean an individual or Legal Entity exercising
|
|
||||||
permissions granted by this License.
|
|
||||||
|
|
||||||
“Source” form shall mean the preferred form for making modifications, including
|
|
||||||
but not limited to software source code, documentation source, and configuration
|
|
||||||
files.
|
|
||||||
|
|
||||||
“Object” form shall mean any form resulting from mechanical transformation or
|
|
||||||
translation of a Source form, including but not limited to compiled object code,
|
|
||||||
generated documentation, and conversions to other media types.
|
|
||||||
|
|
||||||
“Work” shall mean the work of authorship, whether in Source or Object form, made
|
|
||||||
available under the License, as indicated by a copyright notice that is included
|
|
||||||
in or attached to the work (an example is provided in the Appendix below).
|
|
||||||
|
|
||||||
“Derivative Works” shall mean any work, whether in Source or Object form, that
|
|
||||||
is based on (or derived from) the Work and for which the editorial revisions,
|
|
||||||
annotations, elaborations, or other modifications represent, as a whole, an
|
|
||||||
original work of authorship. For the purposes of this License, Derivative Works
|
|
||||||
shall not include works that remain separable from, or merely link (or bind by
|
|
||||||
name) to the interfaces of, the Work and Derivative Works thereof.
|
|
||||||
|
|
||||||
“Contribution” shall mean any work of authorship, including the original version
|
|
||||||
of the Work and any modifications or additions to that Work or Derivative Works
|
|
||||||
thereof, that is intentionally submitted to Licensor for inclusion in the Work
|
|
||||||
by the copyright owner or by an individual or Legal Entity authorized to submit
|
|
||||||
on behalf of the copyright owner. For the purposes of this definition,
|
|
||||||
“submitted” means any form of electronic, verbal, or written communication sent
|
|
||||||
to the Licensor or its representatives, including but not limited to
|
|
||||||
communication on electronic mailing lists, source code control systems, and
|
|
||||||
issue tracking systems that are managed by, or on behalf of, the Licensor for
|
|
||||||
the purpose of discussing and improving the Work, but excluding communication
|
|
||||||
that is conspicuously marked or otherwise designated in writing by the copyright
|
|
||||||
owner as “Not a Contribution.”
|
|
||||||
|
|
||||||
“Contributor” shall mean Licensor and any individual or Legal Entity on behalf
|
|
||||||
of whom a Contribution has been received by Licensor and subsequently
|
|
||||||
incorporated within the Work.
|
|
||||||
|
|
||||||
### 2. Grant of Copyright License
|
|
||||||
|
|
||||||
Subject to the terms and conditions of this License, each Contributor hereby
|
|
||||||
grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free,
|
|
||||||
irrevocable copyright license to reproduce, prepare Derivative Works of,
|
|
||||||
publicly display, publicly perform, sublicense, and distribute the Work and such
|
|
||||||
Derivative Works in Source or Object form.
|
|
||||||
|
|
||||||
### 3. Grant of Patent License
|
|
||||||
|
|
||||||
Subject to the terms and conditions of this License, each Contributor hereby
|
|
||||||
grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free,
|
|
||||||
irrevocable (except as stated in this section) patent license to make, have
|
|
||||||
made, use, offer to sell, sell, import, and otherwise transfer the Work, where
|
|
||||||
such license applies only to those patent claims licensable by such Contributor
|
|
||||||
that are necessarily infringed by their Contribution(s) alone or by combination
|
|
||||||
of their Contribution(s) with the Work to which such Contribution(s) was
|
|
||||||
submitted. If You institute patent litigation against any entity (including a
|
|
||||||
cross-claim or counterclaim in a lawsuit) alleging that the Work or a
|
|
||||||
Contribution incorporated within the Work constitutes direct or contributory
|
|
||||||
patent infringement, then any patent licenses granted to You under this License
|
|
||||||
for that Work shall terminate as of the date such litigation is filed.
|
|
||||||
|
|
||||||
### 4. Redistribution
|
|
||||||
|
|
||||||
You may reproduce and distribute copies of the Work or Derivative Works thereof
|
|
||||||
in any medium, with or without modifications, and in Source or Object form,
|
|
||||||
provided that You meet the following conditions:
|
|
||||||
|
|
||||||
* **(a)** You must give any other recipients of the Work or Derivative Works a copy of
|
|
||||||
this License; and
|
|
||||||
* **(b)** You must cause any modified files to carry prominent notices stating that You
|
|
||||||
changed the files; and
|
|
||||||
* **(c)** You must retain, in the Source form of any Derivative Works that You distribute,
|
|
||||||
all copyright, patent, trademark, and attribution notices from the Source form
|
|
||||||
of the Work, excluding those notices that do not pertain to any part of the
|
|
||||||
Derivative Works; and
|
|
||||||
* **(d)** If the Work includes a “NOTICE” text file as part of its distribution, then any
|
|
||||||
Derivative Works that You distribute must include a readable copy of the
|
|
||||||
attribution notices contained within such NOTICE file, excluding those notices
|
|
||||||
that do not pertain to any part of the Derivative Works, in at least one of the
|
|
||||||
following places: within a NOTICE text file distributed as part of the
|
|
||||||
Derivative Works; within the Source form or documentation, if provided along
|
|
||||||
with the Derivative Works; or, within a display generated by the Derivative
|
|
||||||
Works, if and wherever such third-party notices normally appear. The contents of
|
|
||||||
the NOTICE file are for informational purposes only and do not modify the
|
|
||||||
License. You may add Your own attribution notices within Derivative Works that
|
|
||||||
You distribute, alongside or as an addendum to the NOTICE text from the Work,
|
|
||||||
provided that such additional attribution notices cannot be construed as
|
|
||||||
modifying the License.
|
|
||||||
|
|
||||||
You may add Your own copyright statement to Your modifications and may provide
|
|
||||||
additional or different license terms and conditions for use, reproduction, or
|
|
||||||
distribution of Your modifications, or for any such Derivative Works as a whole,
|
|
||||||
provided Your use, reproduction, and distribution of the Work otherwise complies
|
|
||||||
with the conditions stated in this License.
|
|
||||||
|
|
||||||
### 5. Submission of Contributions
|
|
||||||
|
|
||||||
Unless You explicitly state otherwise, any Contribution intentionally submitted
|
|
||||||
for inclusion in the Work by You to the Licensor shall be under the terms and
|
|
||||||
conditions of this License, without any additional terms or conditions.
|
|
||||||
Notwithstanding the above, nothing herein shall supersede or modify the terms of
|
|
||||||
any separate license agreement you may have executed with Licensor regarding
|
|
||||||
such Contributions.
|
|
||||||
|
|
||||||
### 6. Trademarks
|
|
||||||
|
|
||||||
This License does not grant permission to use the trade names, trademarks,
|
|
||||||
service marks, or product names of the Licensor, except as required for
|
|
||||||
reasonable and customary use in describing the origin of the Work and
|
|
||||||
reproducing the content of the NOTICE file.
|
|
||||||
|
|
||||||
### 7. Disclaimer of Warranty
|
|
||||||
|
|
||||||
Unless required by applicable law or agreed to in writing, Licensor provides the
|
|
||||||
Work (and each Contributor provides its Contributions) on an “AS IS” BASIS,
|
|
||||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied,
|
|
||||||
including, without limitation, any warranties or conditions of TITLE,
|
|
||||||
NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are
|
|
||||||
solely responsible for determining the appropriateness of using or
|
|
||||||
redistributing the Work and assume any risks associated with Your exercise of
|
|
||||||
permissions under this License.
|
|
||||||
|
|
||||||
### 8. Limitation of Liability
|
|
||||||
|
|
||||||
In no event and under no legal theory, whether in tort (including negligence),
|
|
||||||
contract, or otherwise, unless required by applicable law (such as deliberate
|
|
||||||
and grossly negligent acts) or agreed to in writing, shall any Contributor be
|
|
||||||
liable to You for damages, including any direct, indirect, special, incidental,
|
|
||||||
or consequential damages of any character arising as a result of this License or
|
|
||||||
out of the use or inability to use the Work (including but not limited to
|
|
||||||
damages for loss of goodwill, work stoppage, computer failure or malfunction, or
|
|
||||||
any and all other commercial damages or losses), even if such Contributor has
|
|
||||||
been advised of the possibility of such damages.
|
|
||||||
|
|
||||||
### 9. Accepting Warranty or Additional Liability
|
|
||||||
|
|
||||||
While redistributing the Work or Derivative Works thereof, You may choose to
|
|
||||||
offer, and charge a fee for, acceptance of support, warranty, indemnity, or
|
|
||||||
other liability obligations and/or rights consistent with this License. However,
|
|
||||||
in accepting such obligations, You may act only on Your own behalf and on Your
|
|
||||||
sole responsibility, not on behalf of any other Contributor, and only if You
|
|
||||||
agree to indemnify, defend, and hold each Contributor harmless for any liability
|
|
||||||
incurred by, or claims asserted against, such Contributor by reason of your
|
|
||||||
accepting any such warranty or additional liability.
|
|
||||||
@@ -1,16 +0,0 @@
|
|||||||
# pplus-core
|
|
||||||
|
|
||||||
Copyright 2026 Scientific Computing Studio, LLC
|
|
||||||
|
|
||||||
This product includes software developed by Scienting ([scient.ing](https://scient.ing/)).
|
|
||||||
|
|
||||||
Licensed under the Apache License, Version 2.0.
|
|
||||||
See the `LICENSE.md` file for the full license text.
|
|
||||||
|
|
||||||
## Third-party material
|
|
||||||
|
|
||||||
`THIRD_PARTY.md` lists what is not ours: the files under `src/mojo/generated/` and `library/syntax/mojo.xml` that are made from Modular's material, and the tools the build installs and does not redistribute. It also says where the engines under `src/engines/` and the lessons under `src/curriculum/` came from (the course site that runs the same engines); they are ours, under the same license. The submodule `library/` (pplus-library) has its own `LICENSE.md`, `NOTICE.md` and `THIRD_PARTY.md`.
|
|
||||||
|
|
||||||
## Trademarks
|
|
||||||
|
|
||||||
"Mojo" and "Modular" are trademarks of Modular Inc. Programming+ is not affiliated with, sponsored by, or endorsed by Modular Inc.; it uses the names only to say which language and compiler it works with. "Compiler Explorer" and "godbolt.org" name the service by Matt Godbolt that Programming+ asks for the compiler's answers; Programming+ is not affiliated with it either.
|
|
||||||
@@ -1,52 +1,31 @@
|
|||||||
# pplus-core
|
# pplus-core
|
||||||
|
|
||||||
Programming+ takes a procedure from an idea to Mojo to the machine. pplus-core is the part of it that decides what a program means: the notations and the translators between them, the Mojo checker and interpreter, the prover, the fuzzer, the x86-64 machine model, and the tools that hold all of them to the ground truth in pplus-library. It has no DOM and runs in Node as well as in a browser. pplus-web, the site, uses it as a pinned dependency, and `pixi run engines-export` copies the engines into a course's own site.
|
pplus-core is the part of Programming+ that has to be right: the languages, the translators between them, the Mojo checker and interpreter, the prover, the fuzzer, the x86-64 machine model, and the stored answers of the real tools that everything it says rests on. It has no DOM. pplus-web (the site, the editor, the views and the Quarto extension) and the course site use it as a pinned dependency.
|
||||||
|
|
||||||
- **Who it is for:** people who want to change or reuse the engines behind Programming+, or run them without a browser. The site, pplus-web, is where most people meet them.
|
- **Languages:** pseudo (parser, checker, interpreter, the English reader for lingo), matho (equations in LaTeX), speco (specifications), Mojo (a checker and an interpreter held to the real compiler), x86-64 on a model machine with caches, a pipeline and an out-of-order core.
|
||||||
- **Status:** in development, with no tagged release yet ([CHANGELOG.md](CHANGELOG.md)). It works from a clone today: the command line runs and the tests pass.
|
- **Translators:** pseudo to Mojo, lingo, matho and speco, with line maps and located refusals, and the hub that keeps the linked languages in step (`src/sync/`).
|
||||||
- **Try it:** [Quick start](#quick-start). **Run its checks:** `pixi run ci`, or the commands under Quick start without pixi.
|
- **Verification:** the prover (`src/engines/pseudo/logic.ts`, `solver.ts`, `vcgen.ts`), sound and held to it by tests; the fuzzer (`src/common/fuzz.ts`); and a pinned Dafny (`scripts/dafny.py`).
|
||||||
- **Report a problem:** [SECURITY.md](SECURITY.md) says where to send a report and what counts as a security problem (a "proved" that a run breaks is one); [CONTRIBUTING.md](CONTRIBUTING.md) says what makes a good bug report.
|
- **Stored answers:** the Mojo corpus (`mojo/`): material harvested from Modular's repositories at pinned commits, our own probes and programs, and godbolt's answers for every one of them (`mojo/golden/`).
|
||||||
|
|
||||||
Programming+ works in five notations:
|
|
||||||
|
|
||||||
- **lingo**: steps in plain English that a reader can run.
|
|
||||||
- **matho**: equations written in LaTeX.
|
|
||||||
- **pseudo**: pseudocode precise enough to run, prove and translate; every translation goes through it.
|
|
||||||
- **speco**: a specification to prove against: what a routine requires and ensures, and what each loop keeps.
|
|
||||||
- **Mojo**: Modular's programming language, pinned to version 1.2.0. Programming+ writes Mojo from pseudo, steps through it, and asks the real compiler about it.
|
|
||||||
|
|
||||||
What core holds:
|
|
||||||
|
|
||||||
- **Languages:** pseudo (parser, checker, interpreter, and the English reader for lingo), matho, speco, Mojo (a checker and an interpreter held to the real compiler's stored answers), x86-64 on a model machine with caches, a pipeline and an out-of-order core.
|
|
||||||
- **Translators:** pseudo to Mojo, lingo, matho and speco, with line maps and located refusals, and the hub that keeps the linked notations in step (`src/sync/`).
|
|
||||||
- **Verification:** the prover (`src/engines/pseudo/logic.ts`, `solver.ts`, `vcgen.ts`), meant to be sound and held to it by the soundness regressions in `library/pseudo/prover/` (an audit in November 2026 closed 18 rules that proved what a run breaks), a canary, and a run of every corpus program ([docs/engines.md](docs/engines.md#soundness)); the fuzzer (`src/common/fuzz.ts`); and a pinned Dafny (`scripts/dafny.py`).
|
|
||||||
- **A workspace:** `src/common/workspace.ts` is one piece of work and everything its sources mean. pplus-web's session extends it.
|
- **A workspace:** `src/common/workspace.ts` is one piece of work and everything its sources mean. pplus-web's session extends it.
|
||||||
- **The ground truth:** pplus-library, the submodule `library/`, holds what the engines are held to; core also builds its library registry and the exercises' Mojo from it:
|
- **A command line:** `pixi run cli check|run|prove|fuzz|translate <file>`.
|
||||||
- verified routines (statistics, numerics, alignment, molecular simulation, sequences, special functions) that a program brings in with `USE`, each checked by every tool `pixi run library-check` has ([docs/library.md](docs/library.md));
|
|
||||||
- the Mojo corpus (`library/mojo/`): the pin, material harvested from Modular's repositories at pinned commits, our own probes and programs, and godbolt's stored answer for every program we wrote and every harvested program that runs (the compiler's own diagnostic tests are asked only on request) ([docs/mojo-corpus.md](docs/mojo-corpus.md));
|
|
||||||
- pseudo regression programs and the prover's soundness regressions (`library/pseudo/`).
|
|
||||||
- **A command line:** `pixi run cli check|run|prove|fuzz|translate <file>` (`translate` takes `--to mojo`, `lingo`, `matho` or `speco`; `prove` has no time limit unless `--budget-ms` gives one, so it says the same on every machine).
|
|
||||||
|
|
||||||
What core says about Mojo is pinned to **Mojo 1.2.0**. The checker and the interpreter are held to the real compiler's answers on the corpus: to godbolt's stored answers in the tests, and to the pinned compiler on a developer's machine with `pixi run mojo-local` and `mojo-fuzz`, which also build the Mojo the translator writes. On a program outside the corpus the interpreter can still run something the compiler rejects; [docs/trust.md](docs/trust.md) says what each verdict means and what it does not.
|
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
|
## Quick start
|
||||||
|
|
||||||
Clone with the library submodule (`git clone --recurse-submodules`, or `git submodule update --init` in an existing clone). With [pixi](https://pixi.sh) (it brings the pinned Mojo, Node and Python):
|
With [pixi](https://pixi.sh) (it brings the pinned Mojo, Node and Python):
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
pixi run dafny-fetch # once: the pinned Dafny, into .tools/ (network; until then the one test that runs it is skipped)
|
pixi run test # build, then every test
|
||||||
pixi run test # build, then every test
|
pixi run ci # the gate: every test, and no Mojo program of ours failing
|
||||||
pixi run ci # the gate: every test, no Mojo program we wrote failing by godbolt's stored answers, library-check, mojo-local and a short fuzz
|
pixi run cli prove tests/corpus/27-quantifiers.pseudo
|
||||||
pixi run cli prove library/pseudo/programs/19-max-subarray.pseudo # each obligation and its status; the last line is "6 proved, 0 broken, 0 open"
|
pixi run dafny-fetch # once: the pinned Dafny, into .tools/
|
||||||
```
|
```
|
||||||
|
|
||||||
The tests that need a tool that is missing (the fetched Dafny, `python3`, a C compiler `cc` for the library's C references) are skipped and say so; under CI they fail instead ([docs/ci.md](docs/ci.md)).
|
Without pixi, with Node 20 or later (and `python3` for the pipelines' tests):
|
||||||
|
|
||||||
Without pixi, with Node (`package.json` asks for 20 or later; the tests run on Node 26.10, which pixi pins) and `python3` for the pipelines' tests:
|
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
npm install && npm test
|
npm install && npm test
|
||||||
python3 scripts/mojo/corpus.py status --strict
|
|
||||||
```
|
```
|
||||||
|
|
||||||
## Commands
|
## Commands
|
||||||
@@ -62,47 +41,35 @@ Every command is a pixi task (`pixi task list` shows them with their description
|
|||||||
| `check` | Type-check only |
|
| `check` | Type-check only |
|
||||||
| `test` | Build, then run every test, the pipelines' Python tests included |
|
| `test` | Build, then run every test, the pipelines' Python tests included |
|
||||||
| `cli` | `pplus check\|run\|prove\|fuzz\|translate <file>`: core without a browser ([scripts/cli.mjs](scripts/cli.mjs)) |
|
| `cli` | `pplus check\|run\|prove\|fuzz\|translate <file>`: core without a browser ([scripts/cli.mjs](scripts/cli.mjs)) |
|
||||||
| `prove-fuzz` | Fuzz the prover: random procedures with contracts are proved, then run; fail on a proved obligation a run breaks ([docs/engines.md](docs/engines.md#soundness)) |
|
|
||||||
| `engines-diff <static>` | Show what a course checkout has not taken yet from the engines ([docs/engines.md](docs/engines.md)) |
|
| `engines-diff <static>` | Show what a course checkout has not taken yet from the engines ([docs/engines.md](docs/engines.md)) |
|
||||||
| `engines-export <static>` | Copy the engines into a course checkout, TypeScript modules as built ([docs/engines.md](docs/engines.md)) |
|
| `engines-export <static>` | Copy the engines into a course checkout, TypeScript modules as built ([docs/engines.md](docs/engines.md)) |
|
||||||
| **Dafny, pinned** ([scripts/dafny.py](scripts/dafny.py)) | |
|
| **Dafny, pinned** ([scripts/dafny.py](scripts/dafny.py)) | |
|
||||||
| `dafny-fetch` | Download the pinned Dafny into `.tools/`, checked by SHA-256 (network, once) |
|
| `dafny-fetch` | Download the pinned Dafny into `.tools/`, checked by SHA-256 (network, once) |
|
||||||
| `dafny` | Run the pinned Dafny with the arguments given, e.g. `pixi run dafny verify file.dfy` |
|
| `dafny` | Run the pinned Dafny with the arguments given, e.g. `pixi run dafny verify file.dfy` |
|
||||||
| **The library** ([docs/library.md](docs/library.md)) | |
|
|
||||||
| `library-check` | Check every library routine at every level; writes `library/status.json` and `STATUS.md` |
|
|
||||||
| `library-emit` | Regenerate `src/library/generated.ts`, the registry `USE` reads, from `library/` |
|
|
||||||
| `library-verify-mojo` | Ask the pinned Mojo compiler about every Mojo reference of the library (network) |
|
|
||||||
| `library-harness <id> <lang> <level>` | Print the program a reference implementation is run as |
|
|
||||||
| `library-harness-input <id> <lang> <level>` | Print the line of stdin a C or Mojo reference's program reads (its cases arrive at run time) |
|
|
||||||
| **Write content** | |
|
| **Write content** | |
|
||||||
| `new-exercise <id>` | Start an exercise whose Mojo lives in `library/mojo/local/<id>.mojo` ([docs/exercises.md](docs/exercises.md)) |
|
| `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 `library/mojo/probes/<name>.mojo`: one question about the compiler ([docs/mojo-corpus.md](docs/mojo-corpus.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 `library/mojo/stress/<name>.mojo`: realistic Mojo that tests the interpreter |
|
| `new-stress <name> <about>` | Start `mojo/stress/<name>.mojo`: realistic Mojo that tests the interpreter |
|
||||||
| `play <name>` | For `library/mojo/local/<name>.mojo`: run, verify on godbolt, build, list the assembly, test |
|
| `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) |
|
| `play-watch <name>` | The same, again on every save (tests off) |
|
||||||
| **The Mojo corpus** ([docs/mojo-corpus.md](docs/mojo-corpus.md)) | |
|
| **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` | 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-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-dry` | Show what `mojo-verify` would send; send nothing |
|
||||||
| `mojo-verify-diagnostics` | Also check the compiler's own diagnostic tests (opt-in; network) |
|
| `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 `library/mojo/golden/STATUS.md` |
|
| `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-status-strict` | The same, and fail if a program we wrote fails |
|
||||||
| `mojo-prune` | Remove stored answers nothing reads any more: another compiler's, and those of edited or removed programs |
|
| `mojo-harvest` | After editing `mojo/pin.json`: fetch Modular's sources, process, regenerate (network) |
|
||||||
| `mojo-harvest` | After editing `library/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-local [dir]` | Harvest, with zips standing in for sources the pin leaves unresolved |
|
||||||
| `mojo-harvest-offline [dir]` | Harvest from zips only, no network |
|
| `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-fetch` | Re-resolve every ref in the pin and rewrite the lock (network) |
|
||||||
| `mojo-emit` | Regenerate `src/mojo/generated/` and `library/syntax/mojo.xml` from the pin and corpus, offline |
|
| `mojo-emit` | Regenerate `src/mojo/generated/` and `syntax/mojo.xml` from the pin and corpus, offline |
|
||||||
| `mojo-test` | The corpus pipeline's own tests |
|
| `mojo-test` | The corpus pipeline's own tests |
|
||||||
| `mojo-run <file>` | Run one Mojo file on the pinned local compiler, built with the pin's build arguments and then its own |
|
| `mojo-run <file>` | Run one Mojo file on the pinned local compiler |
|
||||||
| `mojo-local` | Build every Mojo program core holds or generates on the pinned local compiler; hold the checker, interpreter and translator to it |
|
|
||||||
| `mojo-fuzz` | Fuzz the translator, the checker and the interpreter against the pinned local compiler with generated programs |
|
|
||||||
| `mojo-probes-local` | Run every probe on the local compiler (a quick look) |
|
| `mojo-probes-local` | Run every probe on the local compiler (a quick look) |
|
||||||
| `mojo-update` | After editing the pin: harvest, verify, status, test |
|
| `mojo-update` | After editing the pin: harvest, verify, status, test |
|
||||||
| **Ship** | |
|
| **Ship** | |
|
||||||
| `ci` | What CI runs: every test, and no program of ours failing |
|
| `ci` | What CI runs: every test, and no program of ours failing |
|
||||||
| `ci-fuzz` | The fuzzers' share of `ci`: `mojo-fuzz` and `prove-fuzz` on seed 1 and on a seed that moves, each printed ([docs/ci.md](docs/ci.md)) |
|
|
||||||
| `nightly` | What the scheduled CI runs: `mojo-status-strict`, and the fuzzers longer on four seeds that move with the date |
|
|
||||||
| `package` | Zip what git tracks, and nothing it ignores, into `package/` for sharing |
|
| `package` | Zip what git tracks, and nothing it ignores, into `package/` for sharing |
|
||||||
|
|
||||||
## Where things are
|
## Where things are
|
||||||
@@ -112,22 +79,18 @@ AGENTS.md rules for changing core (read first)
|
|||||||
src/
|
src/
|
||||||
common/ the workspace, the problem catalog, the fuzzer, the run view's data, the language
|
common/ the workspace, the problem catalog, the fuzzer, the run view's data, the language
|
||||||
reference, the machine presets, the shared types
|
reference, the machine presets, the shared types
|
||||||
library/ the registry USE reads (generated from library/), and its types
|
engines/pseudo/ the pseudo language and the prover (logic, solver, vcgen in TypeScript), and the course's
|
||||||
engines/pseudo/ the pseudo language and the prover (logic, solver, vcgen in TypeScript), and a course's
|
|
||||||
page widgets for it (excluded from the build; see docs/engines.md)
|
page widgets for it (excluded from the build; see docs/engines.md)
|
||||||
engines/asm86/ the x86-64 model machine, and a course's widgets that draw it (views, hwviews)
|
engines/asm86/ the x86-64 model machine, and the course's widgets that draw it (views, hwviews)
|
||||||
engines/shared/ text helpers, and a course's DOM helpers
|
engines/shared/ text helpers, and the course's DOM helpers
|
||||||
services/ one adapter per language behind LanguageService; the compiler request and backend
|
services/ one adapter per language behind LanguageService; the compiler request and backend
|
||||||
sync/ the translators and the hub that keeps the linked languages in step
|
sync/ the translators and the hub that keeps the linked languages in step
|
||||||
mojo/ the Mojo checker, interpreter, lifetimes, practices, AT&T-to-Intel; generated/ from the corpus
|
mojo/ the Mojo checker, interpreter, lifetimes, practices, AT&T-to-Intel; generated/ from the corpus
|
||||||
exercises/ one file per catalog problem
|
exercises/ one file per catalog problem
|
||||||
curriculum/ a lesson corpus kept as an interpreter fixture
|
curriculum/ a lesson corpus kept as an interpreter fixture
|
||||||
library/ pplus-library, a git submodule: the ground truth
|
syntax/mojo.xml the Mojo words as a KDE syntax for Pandoc (generated; pplus-web copies it)
|
||||||
modules/ verified routines that programs bring in with USE
|
tests/ node --test against dist/; corpus/ (pseudo programs), prover/ (soundness regressions)
|
||||||
mojo/ the Mojo corpus: the pin and lock, harvested material, our programs, godbolt's answers
|
mojo/ the Mojo corpus: the pin and lock, harvested material, our programs, godbolt's answers
|
||||||
pseudo/ programs/ (pseudo regression programs), prover/ (soundness regressions)
|
|
||||||
syntax/mojo.xml the Mojo words as a KDE syntax for Pandoc (generated; pplus-web copies it)
|
|
||||||
tests/ node --test against dist/, over the programs in library/ and the cases in each test
|
|
||||||
scripts/ the tasks above; scripts/mojo/ is the corpus pipeline; dafny.py the Dafny pin; cli.mjs
|
scripts/ the tasks above; scripts/mojo/ is the corpus pipeline; dafny.py the Dafny pin; cli.mjs
|
||||||
docs/ the documents below
|
docs/ the documents below
|
||||||
```
|
```
|
||||||
@@ -137,16 +100,9 @@ docs/ the documents below
|
|||||||
| Document | For |
|
| Document | For |
|
||||||
|---|---|
|
|---|---|
|
||||||
| [AGENTS.md](AGENTS.md) | Rules for anyone changing core, coding agents included: the gate, what not to edit, conventions |
|
| [AGENTS.md](AGENTS.md) | Rules for anyone changing core, coding agents included: the gate, what not to edit, conventions |
|
||||||
| [docs/engines.md](docs/engines.md) | The engines, the prover and its soundness, and how a course's site takes them |
|
| [docs/engines.md](docs/engines.md) | The engines, the prover and its soundness, and how the course takes them |
|
||||||
| [docs/trust.md](docs/trust.md) | Every verdict core produces: which tool earns it, what it means, and what it does not mean |
|
| [docs/trust.md](docs/trust.md) | Every verdict core produces: which tool earns it, what it means, and what it does not mean |
|
||||||
| [docs/limits.md](docs/limits.md) | Where each reader and each run stops on text from a share link, and what the student sees then |
|
|
||||||
| [docs/ci.md](docs/ci.md) | What CI and the nightly run do, and what to do when they fail |
|
|
||||||
| [docs/mojo-corpus.md](docs/mojo-corpus.md) | Writing Mojo of our own and moving to a new Mojo version |
|
| [docs/mojo-corpus.md](docs/mojo-corpus.md) | Writing Mojo of our own and moving to a new Mojo version |
|
||||||
| [docs/library.md](docs/library.md) | The library: USE, what each check of a routine means, and changing it |
|
|
||||||
| [docs/exercises.md](docs/exercises.md) | Adding a catalog problem |
|
| [docs/exercises.md](docs/exercises.md) | Adding a catalog problem |
|
||||||
| [docs/sync-coverage.md](docs/sync-coverage.md) | What each translator can say, written by the tests |
|
| [docs/sync-coverage.md](docs/sync-coverage.md) | What each translator can say, written by the tests |
|
||||||
| [docs/asm-coverage.md](docs/asm-coverage.md) | Which instructions compiled Mojo uses, against what the machine models |
|
| [docs/asm-coverage.md](docs/asm-coverage.md) | Which instructions compiled Mojo uses, against what the machine models |
|
||||||
|
|
||||||
## License
|
|
||||||
|
|
||||||
Copyright 2026 Scientific Computing Studio, LLC, under the Apache License 2.0 ([LICENSE.md](LICENSE.md)); [NOTICE.md](NOTICE.md) has the notices and a disclaimer of affiliation with Modular, and [THIRD_PARTY.md](THIRD_PARTY.md) lists what is not ours and its licenses.
|
|
||||||
-16
@@ -1,16 +0,0 @@
|
|||||||
# Security
|
|
||||||
|
|
||||||
pplus-core reads programs and runs them inside its own interpreters: pseudo, Mojo and x86-64 are interpreted by JavaScript written here, with a step limit, and nothing a program says is ever handed to JavaScript's `eval` or to a shell.
|
|
||||||
The prover and the fuzzer work on the same trees.
|
|
||||||
A program that makes an engine crash (an exception escapes), hang past its step or time limits, use memory without bound, or reach anything outside the program's own state is a security issue, because pplus-web runs these engines on whatever a link carries.
|
|
||||||
So is a "proved" verdict for something a run breaks, which is a soundness bug: it would let a student trust a wrong program.
|
|
||||||
|
|
||||||
Some tasks run real tools on your machine, and those run what you give them: `pixi run mojo-local`, `mojo-fuzz` and `library-check` build and run Mojo, C and Python programs from this repository and from the library, and `mojo-verify`, `mojo-verify-item`, `play` and `library-verify-mojo` send the corpus's programs and the library's Mojo references to godbolt.org.
|
|
||||||
Run them on a checkout you trust.
|
|
||||||
|
|
||||||
Report a problem to Alex M. Maldonado at alex@scient.ing, with the program that shows it and what happened.
|
|
||||||
You will get an acknowledgment within a week.
|
|
||||||
We promise no response time beyond that; one person maintains Programming+.
|
|
||||||
Please do not open a public issue for a problem that could hurt someone else until a fix is out.
|
|
||||||
|
|
||||||
Only the latest commit on `main` gets fixes.
|
|
||||||
@@ -1,51 +0,0 @@
|
|||||||
# Third-party material in pplus-core
|
|
||||||
|
|
||||||
Everything in this repository is ours, under the Apache License 2.0 ([LICENSE.md](LICENSE.md)), except what this file lists. `tests/third-party.test.mjs` holds the versions and licenses below to `package-lock.json`, `pixi.lock` and `scripts/dafny.py`, and holds the list of generated files to `src/mojo/generated/`, so a change there fails the tests until this file says so.
|
|
||||||
|
|
||||||
## The library
|
|
||||||
|
|
||||||
`library/` is pplus-library, a repository of its own pinned as a submodule. Its [THIRD_PARTY.md](library/THIRD_PARTY.md), written by `pixi run mojo-emit`, lists every file harvested from Modular's repositories (`library/mojo/corpus/`), its source commit and the license header it carries, and the license file of each source at the pinned commit (`library/mojo/licenses/`).
|
|
||||||
|
|
||||||
## Made here from Modular's material, and shipped in the app
|
|
||||||
|
|
||||||
`pixi run mojo-emit` writes these from the corpus. Each file's first lines name the commit it came from.
|
|
||||||
|
|
||||||
| File | Made from | What it is |
|
|
||||||
|---|---|---|
|
|
||||||
| `src/mojo/generated/tokens.ts` | modular/modular: `TokenKinds.def`, `lib/MojoParser`, the decorator reference, the stdlib prelude (Apache-2.0 WITH LLVM-exception) | Lists of the language's words: keywords, soft keywords, punctuation, decorators, prelude names, the words 1.x removed. Two messages, for `fn` and `read`, are the compiler's own wording, quoted from its source. |
|
|
||||||
| `src/mojo/generated/stdlib.ts` | modular/modular: `stdlib/std` (Apache-2.0 WITH LLVM-exception) | Which package exports each public standard-library name: names and module paths, no code. |
|
|
||||||
| `src/mojo/generated/types.ts` | modular/modular: `stdlib/std` (Apache-2.0 WITH LLVM-exception) | Each standard struct's and trait's name, the traits it declares, and the names of the methods a trait gives by default: names and relations, no code. |
|
|
||||||
| `src/mojo/generated/editor.ts` | modular/vscode-mojo: `language-configuration.json` (Apache-2.0) | The comment marker, bracket pairs and indentation patterns an editor uses for Mojo: a few configuration values. |
|
|
||||||
| `src/mojo/generated/pin.ts` | `library/mojo/pin.json` and the lock | The Mojo version, the godbolt compiler id and the source commits: ours. |
|
|
||||||
| `src/mojo/generated/programs.ts` | `library/mojo/local/` and `library/mojo/golden/` | Our own exercise programs, each with the verdict Compiler Explorer's answer gave it. |
|
|
||||||
| `src/mojo/generated/listings.ts` | `library/mojo/golden/` (written by `pixi run play`) | The Mojo compiler's assembly listing for each of our exercise programs, as Compiler Explorer returned it. |
|
|
||||||
| `library/syntax/mojo.xml` | the same words as `tokens.ts` | A KDE syntax definition for Pandoc listings. Its header attribute says `license="Apache-2.0"`, which `scripts/mojo/mojocorpus/kde.py` writes. |
|
|
||||||
|
|
||||||
The Mojo checker (`src/mojo/`) reports some errors in the compiler's own words (for example "use of unknown declaration"), so that a student sees the message the compiler would print; `tests/mojo-check.test.mjs` holds them to the compiler's stored answers. These are short phrases, written into our code by hand.
|
|
||||||
|
|
||||||
## Stored compiler answers
|
|
||||||
|
|
||||||
`library/mojo/golden/` (in pplus-library) holds the answer [Compiler Explorer](https://godbolt.org) returned for each program it was asked about: what the Mojo compiler printed, its exit code and, for some, its assembly. The programs are ours (probes, exercises, stress programs, the library's references) and the harvested corpus. Compiler Explorer is BSD-2-Clause software run by Matt Godbolt and volunteers; its [privacy policy](https://github.com/compiler-explorer/compiler-explorer/blob/main/static/generated/privacy.pug) says it caches compilation results and deletes source code within minutes, and neither the site nor its [API documentation](https://github.com/compiler-explorer/compiler-explorer/blob/main/docs/API.md) states terms of use for its answers.
|
|
||||||
|
|
||||||
## The engines and the lessons, which came from the course
|
|
||||||
|
|
||||||
`src/engines/` (the pseudo, asm86 and shared modules, and the course's page widgets beside them) and `src/curriculum/` (a lesson corpus kept as an interpreter fixture) come from the course site that also runs these engines. [docs/engines.md](docs/engines.md) says the engines "started as a copy of the course's modules" and that this repository now owns them. They are listed here to say where they came from, not because they are someone else's: both are Copyright Scientific Computing Studio, LLC, under the Apache License 2.0, like the rest of the repository.
|
|
||||||
|
|
||||||
## Installed to build and test, not redistributed
|
|
||||||
|
|
||||||
pixi installs these into `.pixi/`, npm into `node_modules/`, and `scripts/dafny.py` into `.tools/`; git ignores all three. No compiler binary, runtime library or standard-library source of Mojo is in this repository or in its history.
|
|
||||||
|
|
||||||
| Tool | Version | From | License | In what we ship |
|
|
||||||
|---|---|---|---|---|
|
|
||||||
| Mojo (`mojo`, `mojo-compiler`, `mojo-python`, `mblack`) | 1.2.0 | conda.modular.com, by pixi | LicenseRef-Modular-Proprietary (Modular's license, as `pixi.lock` records it) | Nothing. Tasks run the compiler on our programs. |
|
|
||||||
| Node.js | 26.10.0 | conda-forge, by pixi | MIT | Nothing. |
|
|
||||||
| Python | 3.14.7 | conda-forge, by pixi | Python-2.0 | Nothing. The pipelines use its standard library. |
|
|
||||||
| GCC (`gcc`, on Linux only) | 16.2.0 | conda-forge, by pixi | GPL-3.0-only WITH GCC-exception-3.1 (the compiler, `gcc_impl_linux-64`), with binutils (GPL-3.0-only) and the headers and C library it builds against (LGPL-2.0-or-later) | Nothing. It links the programs `mojo build` makes and builds the C references `library-check` runs and one test's harness; the programs are ours, and no binary is kept. |
|
|
||||||
| TypeScript | 6.0.3 | npm (`package-lock.json`) | Apache-2.0 | Nothing. `tsc` compiles `src/`; the output is our code. |
|
|
||||||
| Dafny | 4.11.0 | the GitHub release zip, by `scripts/dafny.py`, checked by SHA-256 | MIT (Dafny and the Z3 it carries, with .NET runtime files; Dafny's own NOTICES.txt lists the rest) | Nothing. Its verdicts are stored in `library/modules/*/*/golden/dafny.json`. |
|
|
||||||
|
|
||||||
The other packages pixi installs come with these from conda-forge; `pixi.lock` names each with its license.
|
|
||||||
|
|
||||||
## Names
|
|
||||||
|
|
||||||
"Mojo" and "Modular" are trademarks of Modular Inc. Programming+ is not affiliated with or endorsed by Modular. "Compiler Explorer" and "godbolt.org" name the service by Matt Godbolt that the app asks.
|
|
||||||
+11
-13
@@ -1,27 +1,25 @@
|
|||||||
# The model machine against compiled Mojo
|
# 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 (`library/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.
|
"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
|
## Where it stands
|
||||||
|
|
||||||
| | before | now |
|
| | before | now |
|
||||||
|---|---|---|
|
|---|---|---|
|
||||||
| distinct instructions in the listings | 97 | 104 |
|
| distinct instructions in the listings | 97 | 97 |
|
||||||
| of which outside the model's set | 38 | 6 (all 256-bit AVX2: `vextracti128`, `vinserti128`, `vpblendvb`, `vperm2i128`, `vpalignr`, `vptest`) |
|
| 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) | 17 of 17 |
|
| the user's own functions that assemble | 3 of 7 (`main` never did) | 7 of 7 |
|
||||||
| standard-library and runtime functions that assemble | — | 698 of 733 |
|
| standard-library and runtime functions that assemble | — | 438 of 467 |
|
||||||
|
|
||||||
The "before" column is the census of the listings the corpus held when this work began; the "now" column is today's census of today's listings, and `tests/documents.test.mjs` fails when it no longer matches `node scripts/asm-census.mjs`. Every listing is built for `--target-cpu x86-64-v3` (the pin's build arguments, [mojo-corpus.md](mojo-corpus.md#how-every-program-is-built)), so it holds AVX2 at most and never AVX-512, whichever of godbolt's machines answered; `tests/build-args.test.mjs` fails on a listing with a `zmm` or mask register. Asked again under those arguments, every listing the corpus held came back with the same instructions; `vptest` and four modeled ones (`adc`, `cmovle`, `jns`, `tzcnt`) came with `probes/godbolt-target-cpu`, String's `==` at the default optimization level.
|
`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.
|
||||||
|
|
||||||
`main()` now steps up to its first call into `print` and stops there 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
|
## 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 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 optimizer likes.** Added, each with a one-sentence gloss for the datapath view and the micro-op model told what it reads and writes:
|
**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 modeled)
|
- 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
|
- 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`
|
- 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"
|
- `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"
|
||||||
@@ -34,7 +32,7 @@ The "before" column is the census of the listings the corpus held when this work
|
|||||||
|
|
||||||
## Scalar doubles, parity, shld (added)
|
## 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 modeled.
|
- `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).
|
- `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.
|
- 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.
|
- `shld`/`shrd` on 32- and 64-bit operands; count masked to 5/6 bits; count 0 changes nothing, flags included.
|
||||||
@@ -42,10 +40,10 @@ The "before" column is the census of the listings the corpus held when this work
|
|||||||
|
|
||||||
## What stays outside, and why
|
## What stays outside, and why
|
||||||
|
|
||||||
- **256-bit AVX2 (`ymm`)**: the model keeps sixteen 128-bit `xmm` registers and no `ymm` halves; the six instructions above are used only in that width. A `ymm` operand is refused with that sentence. Modeling 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.
|
- **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.
|
- **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.
|
- **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
|
## Keeping it honest
|
||||||
|
|
||||||
The census runs against whatever the corpus holds: every stored answer that carries a listing (the probes and exercise programs whose header asks for `mode: asm` or `mode: both`). `pixi run mojo-verify` on a new such program adds its listing, and each addition either assembles or fails `tests/asm-coverage.test.mjs` with the instruction named. That test's ratchet (`LIBRARY_AT_LEAST`) is a floor under the table's library count; raise it when the machine learns more, never lower it.
|
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.
|
||||||
-62
@@ -1,62 +0,0 @@
|
|||||||
# CI
|
|
||||||
|
|
||||||
CI runs what a developer runs. Every workflow installs pixi, restores the environment `pixi.lock` pins (Node, Python, the Mojo compiler, and a C compiler on Linux) with `pixi install --locked`, and runs a pixi task, so the gate on the runner and the gate on a laptop are the same command in the same environment. Five weeks once passed with `main` broken in two places and nobody told: CI then ran `npm ci && npm test` with whatever Node the host had, no pandoc, no Mojo compiler and no Dafny, and a missing tool skipped tests in silence.
|
|
||||||
|
|
||||||
| Workflow | When | Runs | Time here |
|
|
||||||
|---|---|---|---|
|
|
||||||
| `.gitea/workflows/test.yml` | every push and pull request, on the `heavy` runner | `pixi run ci`, then checks that nothing the gate regenerates differs from what is committed | 4 minutes here, 2.5 with `mojo-local`'s answers cached |
|
|
||||||
| `.gitea/workflows/nightly.yml` | every day at 06:17 UTC, and by hand, on the `heavy` runner | `pixi run nightly` | 12 minutes here |
|
|
||||||
| pplus-library's `.gitea/workflows/test.yml` | every push and pull request to the library, on the `heavy` runner | core's default branch with that library commit in `library/`, then `pixi run ci` (below) | as core's |
|
|
||||||
|
|
||||||
`pixi run ci` is `test` (every test), `mojo-status-strict` (no Mojo program of ours fails, from godbolt's stored answers), `library-check` (every library routine at every level, Dafny included), `mojo-local` (every Mojo program core holds or generates, built and run by the pinned compiler) and `ci-fuzz` (below). `pixi run nightly` is `mojo-status-strict` and the fuzzers for longer.
|
|
||||||
|
|
||||||
## The runner
|
|
||||||
|
|
||||||
The gate is heavy: it builds and runs some 300 Mojo programs, checks every library routine and fuzzes, about 4 minutes on a 24-core workstation, and 4 and a half on two cores in the deploy runner's image with nothing cached. So the workflows run on a runner with the label `heavy`, a machine with cores to spare, and never on the server that deploys the site (pplus-web's deploy job, label `quarto-deploy`, runs the site's own tests and nothing of this gate). While no `heavy` runner is registered a run waits, and the next push's run replaces it; until one is, the gate is `pixi run ci` on a developer's machine before a push.
|
|
||||||
|
|
||||||
Registering one, on the machine that will run it (a Gitea act_runner, as its documentation describes: download it, `act_runner generate-config > config.yaml`, run it as a service under a user of its own):
|
|
||||||
|
|
||||||
```bash
|
|
||||||
# in a container, the image the deploy runner uses (anything with git, Node, curl, tar and bash will do):
|
|
||||||
act_runner register --instance https://<your-gitea> --token <runner token> --no-interactive \
|
|
||||||
--labels "heavy:docker://<your-gitea-host>/infra/quarto-deploy:1.9.38"
|
|
||||||
# or on the machine's own shell (host mode), where the caches below last from job to job:
|
|
||||||
act_runner register --instance https://<your-gitea> --token <runner token> --no-interactive --labels "heavy:host"
|
|
||||||
```
|
|
||||||
|
|
||||||
Take the token from the organization's runner settings, so that pplus-core and pplus-library both see the runner. In `config.yaml`, `runner.capacity` is the number of jobs at once: leave it at 1 unless each job has a cache directory of its own (`.tools/`, below). The workflows use no `container:` and no `services:` of their own, and each needs one change to run on GitHub Actions: `runs-on: ubuntu-latest` in place of the label. A pull request from a fork would run its own code on that machine; each job's `if:` runs pull requests only from branches of the repository itself.
|
|
||||||
|
|
||||||
- **pixi.** `PIXI_VERSION` at the top of each workflow is the pixi that reads the lock. The first step uses the runner's pixi when it is that version; otherwise it downloads that release from GitHub into `$PPLUS_CI_CACHE/pixi-<version>/` (default `~/.cache/pplus-ci`), checks its SHA-256 (written in the workflow), and puts it on the PATH. No sudo. A runner that keeps its home between jobs (host mode) fetches it once; a container fetches it in every job. To move pixi: change `PIXI_VERSION` and both hashes in every workflow, in one commit, and check that `pixi install --locked` still accepts the lock.
|
|
||||||
- **The environment.** `pixi install --locked` fails if `pixi.toml` and `pixi.lock` disagree, so the runner never resolves anything new. On Linux the environment has a C compiler (`gcc` from conda-forge, which is also `cc` on the PATH), because `mojo build` links every program with the C compiler it finds and stops with "unable to find suitable c compiler for linking" when there is none, as in a slim container image; `library-check` builds the C references with it and one test a C harness. The C library it links against is pinned too (`sysroot_linux-64` 2.34): Mojo 1.2.0's runtime libraries need glibc 2.34, and against conda-forge's default, 2.28, no Mojo program links. So under `pixi run` it is this compiler that links, on a workstation as on the runner, whatever the system has. Where pixi's package cache lasts, each package is downloaded once; a container downloads the whole environment in every job.
|
|
||||||
- **`.tools/`.** The pinned Dafny (`pixi run dafny-fetch`, about 150 MB) and `mojo-local`'s answers live in `.tools/`; in CI `.tools` is a link to `$PPLUS_CI_CACHE/core-tools`, so where that directory lasts neither is fetched or rebuilt on every push. `mojo-local` keys an answer by the compiler's version, the arguments, the input and the whole source, so a cached answer is the compiler's answer for exactly that program. Two jobs that share the cache at once could write the same answer file together; the runner takes one job at a time unless its `capacity` is raised.
|
|
||||||
- **Dafny without ICU.** The release zip carries its own .NET runtime but not ICU, and .NET aborts without it unless told not to look: in the deploy runner's image, which has none, the fetched Dafny printed no version and aborted. `scripts/dafny.py` (and `scripts/library.mjs` and `tests/dafny.test.mjs`, which run the executable themselves) set `DOTNET_SYSTEM_GLOBALIZATION_INVARIANT=1`, and `dafny-fetch` fails if the Dafny it fetched does not start.
|
|
||||||
- **`CI`.** Each workflow sets `CI=true` (Gitea and GitHub set it too). Under it a test that would skip for a missing tool fails instead, because a skip in CI is how a gap hides: python3 (`tests/mojo.test.mjs`, `tests/dafny.test.mjs`, `tests/library.test.mjs`), the fetched Dafny (`tests/dafny.test.mjs`), `cc` (`tests/library-harness.test.mjs`), a git checkout to read the library pointer from (`tests/chain.test.mjs`), and in pplus-web pandoc for the Quarto tests.
|
|
||||||
- **What the runner needs besides pixi:** git, curl, tar, `sha256sum`, bash, and Node for `actions/checkout` itself. Everything else is pinned here: the compilers by `pixi.lock`, Dafny by its hash.
|
|
||||||
- **A slow or busy machine changes how long the gate takes, not what it finds.** The gate first ran on the deploy server, a small virtual machine: the tests that take 20 seconds on a workstation took 15 to 22 minutes there, work that takes 5 milliseconds took more than 3 seconds, and ten tests failed on correct code. Two things in the tests depended on speed then and do not now. A time limit in a test ("this reads in under 2 seconds", there to catch work that grows with the square of its input) is processor time at the machine's pace: `tests/helpers/pace.mjs` times a fixed piece of work and multiplies the limit by how much longer it takes than on the machine the limits were written on, never by less than 1. And the prover's time on the clock, 3 seconds for each routine in the Prove tab, is the caller's: the tests, `pixi run cli prove` and `library-check` give it none, so the counted budgets decide alone and the answer is the same everywhere ([limits.md](limits.md#proving-and-testing)). The fuzzers keep their clock (`--budget-ms`, below): on a slower machine `prove-fuzz` proves less, never more.
|
|
||||||
|
|
||||||
## The fuzzers' seeds
|
|
||||||
|
|
||||||
`pixi run ci-fuzz` runs `mojo-fuzz` (25 programs of expressions), `mojo-fuzz --statements` (25 whole programs) and `prove-fuzz` (300 programs) on two seeds each: seed 1, so a failure that comes back is the same failure, and a seed that moves, so every run looks somewhere new: the CI run's number (`GITHUB_RUN_NUMBER`, which Gitea sets too) or, outside CI, today's date in UTC as `YYYYMMDD`. `pixi run nightly` runs all three on four seeds, the date's number and the three numbers after it, with 100, 100 and 3,000 programs. The size matters: the statement mode's first run at 100 programs a seed found a translator fault (an argument evaluated once per pass of a loop) that many seeds of 40 had not. Every round prints its seed and the command that reproduces it:
|
|
||||||
|
|
||||||
```
|
|
||||||
== prove-fuzz seed 20261113 (reproduce: node scripts/prove-fuzz.mjs --seed 20261113 --programs 3000)
|
|
||||||
```
|
|
||||||
|
|
||||||
and the run ends with a summary, one line per round, `clean`, `FOUND` or `FAILED`.
|
|
||||||
|
|
||||||
## When CI or the nightly run fails
|
|
||||||
|
|
||||||
1. **Find the round.** The summary at the end of the log names it, with its command.
|
|
||||||
2. **Reproduce it here.** Run the same command as a pixi task, with the same seed and size: `pixi run prove-fuzz --seed 20261113 --programs 3000`, or `pixi run mojo-fuzz --seed 20261113 --programs 100`. The same seed makes the same programs on every machine. The prover has a time budget for each routine (`--budget-ms`, 1,500 ms), so a slower machine may prove less than the runner did, never more; if a prove-fuzz finding does not come back, raise the budget.
|
|
||||||
3. **A prove-fuzz finding** is a soundness bug: an obligation marked proved that a run breaks. The report names the program's number and prints the smallest program that still shows it, with the call and the run's seed. `pixi run prove-fuzz --seed S --only-program N --keep work/` writes it as a regression program with its `// CALL:` and `// MUST-NOT-PROVE:` header. Check it by hand (`pixi run cli prove <file>` says proved; running it with that call breaks it), put it in `library/pseudo/prover/`, watch `tests/prover-soundness.test.mjs` fail, then fix the rule (AGENTS.md, rule 5; [engines.md](engines.md#soundness)). `--without <feature>` switches off one construct at a time to see which one the finding needs.
|
|
||||||
4. **A mojo-fuzz finding** is printed once per shape with the smallest expression that shows it; its header (`scripts/mojo/fuzz.mjs`) says what each kind means. A translator fix is pinned in `tests/sync-mojo.test.mjs`; a finding that is the compiler's own is listed there as such, with what was observed.
|
|
||||||
5. **mojo-status-strict** failing means a program we wrote fails against godbolt's stored answers: see [mojo-corpus.md](mojo-corpus.md).
|
|
||||||
6. **Anything else** in `pixi run ci` fails the same way on a developer's machine: run `pixi run ci` and read the first failure.
|
|
||||||
|
|
||||||
A failure opens no issue and sends nothing: the run is red on the repository's Actions page, for whoever looks. Look after a push, and look at the nightly runs at least weekly.
|
|
||||||
|
|
||||||
## The pointer to the library
|
|
||||||
|
|
||||||
Core pins pplus-library as `library/` by commit. `tests/chain.test.mjs` fails when that commit is not in the library checkout, or the checkout is behind it, and says which command fixes it (`git submodule update --init`). The whole chain (web pins core, core pins library; each pointer pushed to its branch; the generated files current; Mojo pinned alike) is checked by pplus-web's `release-check` task, and moved in order by its `release-bump` task (pplus-web's `docs/deploy.md`).
|
|
||||||
|
|
||||||
pplus-library has no tests of its own: its checks are core's. Its workflow checks out core's default branch (or the ref in the repository variable `CORE_REF`), puts the library commit being tested where core's submodule goes, moves core's pointer to it in that throwaway checkout and regenerates what core derives from the library (`library-emit`, `mojo-emit`), and runs `pixi run ci`. A green run shows that core's default branch, given this library and what core regenerates from it, passes core's whole gate. It does not show that core pins this commit (that is a later commit in core), that the site works with it, or anything about a core branch other than the one tested; and a red run can be core's own, so look at core's latest run first.
|
|
||||||
+7
-70
@@ -12,7 +12,7 @@ The engines are wrapped behind one `LanguageService` interface (`src/common/type
|
|||||||
|
|
||||||
## The prover
|
## The prover
|
||||||
|
|
||||||
The prover is three TypeScript modules under strict mode. So are the parser, checker and interpreter it reads from: `ast.ts` states the syntax tree (discriminated unions `Expr` and `Stmt`), the checker's types (`PType`), symbols, run-time values and the trace, and `lang.ts`, `parse.ts`, `check.ts` and `interp.ts` are typed on it; `numeric.ts` (the exact arithmetic, which needs none of it) is TypeScript too. All five were ported with no change in behavior (each stage's results were compared over every pseudo text of the repository and 8,000 mutants of them). The course still receives each as `<name>.js`, built into `dist/engines/pseudo/`. The rest of the pseudo engine (the English reader, analysis, coach, tests, translation, `study`, the course's example programs in `specs` and the vague-word finder in `vague`) and the page widgets are still JavaScript.
|
The prover is three TypeScript modules under strict mode; the rest of the engines are still JavaScript.
|
||||||
|
|
||||||
- `logic.ts`: the term language (a discriminated union, `Term`), the smart constructors that simplify as they build, keys, substitution, linear forms and printing.
|
- `logic.ts`: the term language (a discriminated union, `Term`), the smart constructors that simplify as they build, keys, substitution, linear forms and printing.
|
||||||
- `solver.ts`: the decision procedure, `prove(facts, goal)`. It answers `proved` or `unknown`, never "false". Equalities by union-find with congruence, linear arithmetic over whole numbers by Fourier-Motzkin with integer tightening, case splits, and FORALL used at the positions a case mentions. It is sound and incomplete: products of two unknowns, MOD by an unknown, and most facts about collections are opaque to it.
|
- `solver.ts`: the decision procedure, `prove(facts, goal)`. It answers `proved` or `unknown`, never "false". Equalities by union-find with congruence, linear arithmetic over whole numbers by Fourier-Motzkin with integer tightening, case splits, and FORALL used at the positions a case mentions. It is sound and incomplete: products of two unknowns, MOD by an unknown, and most facts about collections are opaque to it.
|
||||||
@@ -20,47 +20,14 @@ The prover is three TypeScript modules under strict mode. So are the parser, che
|
|||||||
|
|
||||||
"Proved" is about the notation's own number model. INTEGER is a whole number of any size and a FLOAT is a finite number whose rounding the prover does not see into. A run of the interpreter stops where a value leaves that model (a whole number past 2^53 − 1, a FLOAT that is not finite, a division by zero), so every run stays inside what a proof covers. The Mojo made from a program has other limits (a 64-bit `Int` that wraps, a `Float64` that becomes `inf` or `nan`), and a unit whose proof leans on the number model carries an `int-model` or `float-model` note saying so.
|
"Proved" is about the notation's own number model. INTEGER is a whole number of any size and a FLOAT is a finite number whose rounding the prover does not see into. A run of the interpreter stops where a value leaves that model (a whole number past 2^53 − 1, a FLOAT that is not finite, a division by zero), so every run stays inside what a proof covers. The Mojo made from a program has other limits (a 64-bit `Int` that wraps, a `Float64` that becomes `inf` or `nan`), and a unit whose proof leans on the number model carries an `int-model` or `float-model` note saying so.
|
||||||
|
|
||||||
### Numbers
|
|
||||||
|
|
||||||
Pseudo is meant for numerical work, so its number model is stated exactly ([the reference](../src/common/reference.ts) shows every form with a runnable example):
|
|
||||||
|
|
||||||
| Type | Holds | When a result does not fit | The prover |
|
|
||||||
|---|---|---|---|
|
|
||||||
| `INTEGER` | A whole number of any size; a run holds it exactly to 2^53 − 1 | The run stops past 2^53 − 1, also when the number comes from a FLOAT (`INT`, `ROUND`, `FLOOR`, `CEIL`), from SUM, on a FOR counter, and from INPUT or `TO_INTEGER` | Exact arithmetic of any size; an `int-model` note says the lab's and Mojo's limits are not part of the proof |
|
|
||||||
| `INT8` … `INT64`, `UINT8` … `UINT64` | Two's complement or unsigned, n bits (64-bit types held exactly to 2^53 − 1 in this lab) | The run stops (kind `overflow`); `WRAP(X, T)` wraps on purpose (up to 32 bits) | Exact arithmetic plus an `overflow` obligation on every result, store, parameter, RETURN, conversion and declared FOR counter: "fits INT8". After it, the range is a fact. A sized parameter and a sized variable cut by a loop keep their range |
|
|
||||||
| `FLOAT`, `FLOAT64` | IEEE 754 double | The run stops on infinity or NaN | `FLOAT+` and its kind are uninterpreted: the same operation on the same values gives the same result, nothing more |
|
|
||||||
| `FLOAT32` | IEEE 754 single: every result rounded to 24 bits (`Math.fround`, exact for +, −, ×, ÷ of singles) | As FLOAT | Its own uninterpreted functions (`F32+`, ...); a constant is rounded exactly; a value that becomes a FLOAT32 is `TOFLOAT32(v)`, about which nothing is assumed |
|
|
||||||
|
|
||||||
Rules the checker holds: two different sized types never mix silently (`mixed-width`, `mixed-precision`; convert with `INT32(X)`, `FLOAT32(X)`); a numeric literal takes the type of the sized value beside it, as in Mojo, and a whole-number literal that does not fit is an error before any run (`literal-range`); INTEGER may go into a sized type (checked when it happens), never a different sized type.
|
|
||||||
|
|
||||||
`USE IEEE` lets NaN and the infinities flow as IEEE 754 says (SQRT(−1.0) is NaN, 1.0 / 0.0 is infinity; whole-number division by zero still stops). Where IEEE 754 says what a built-in gives, that is what a run gives: `MIN` and `MAX` with a NaN among their values are NaN wherever it stands (754-2019 `minimum` and `maximum`), `ULP` of an infinity is infinity (as Python's `math.ulp`; 754 defines no ulp), `^` and `POW` follow 754's `pow` (1 to any power, NaN included, is 1, and so is −1 to an infinite power), and `SORTED` puts NaN last. The prover's reasoning about numbers does not hold for those values, so in such a program nothing is marked proved, and each unit carries an `ieee` note. Without it, NaN and the infinities do not enter a run from outside either: a call's argument (`run()` with `call`) that is or holds one for a FLOAT parameter stops the run before the call (kind `value`).
|
|
||||||
|
|
||||||
What is exact or correctly rounded, and what is not: `FMA`, `ULP`, `NEXT_AFTER`, `EXACT`, `SQRT`, the conversions (`FLOAT32(X)`, `INT32(X)`, a decimal literal that becomes a FLOAT32), `MAX_VALUE`, `EPSILON`, the bit operations, `GCD`, `LCM`, `CHOOSE`, `DIV` and `MOD`, and `+`, `-`, `*`, `/` are: `src/engines/pseudo/numeric.ts` computes `FMA` with one rounding by exact binary arithmetic, `EXACT(X)` gives every decimal digit a FLOAT holds, and `ULP` and `NEXT_AFTER` step through the representation. The elementary functions (`EXP`, `LOG` and its kind, `EXPM1`, `LOG1P`, `CBRT`, `HYPOT`, the trigonometric and hyperbolic ones, `POW` and `^` with a FLOAT) are the JavaScript engine's: within one unit in the last place of the correctly rounded value in almost every case (`HYPOT` within two), not always equal to it (`EXPM1(1.0)` is 1.718281828459045, where the nearest FLOAT is 1.7182818284590453). The statistics (`SUM_OF`, `MEAN_OF`, `VARIANCE_OF`, `STDEV_OF`, `MEDIAN_OF`, `DOT`, `NORM_OF`) are the plain left-to-right sums a loop would compute, with that loop's rounding and its overflow on the way: over whole numbers every product and partial sum is checked as `*` and `+` check theirs (`DOT([94906267, 1], [94906267, -9007199254740991])` stops, though the total fits), over FLOATs each is rounded in turn; `MEDIAN_OF` sorts and takes the middle value or the mean of the two middle ones (`NORM_OF` of one value past about 1.34e154 stops, since its square passes the largest FLOAT, `SUM_OF([1e16, 1.0, -1e16])` is 0.0); a lesson on compensated summation writes its own. `IS_CLOSE` evaluates its formula in FLOAT arithmetic, as Python's `math.isclose` does. `DIV` and `MOD` are floored: the remainder has the divisor's sign (`-7 DIV 2` is -4, `-7 MOD 2` is 1). The arithmetic inside `WRAP(...)` is exact only to 2^53 - 1, so a product of two 32-bit values can stop there before it is wrapped. Functions JavaScript has no exact version of (erf, gamma) are not built-ins; they belong in the library as verified pseudo. These built-ins carry an `argument` obligation that their arguments are allowed: SQRT, the logarithms, ASIN and ACOS, LOG1P, CLAMP, the shifts, `FILL` and `RANDINT`. Others that stop the run for some arguments (`MIN`, `MAX` and `MEAN_OF` of an empty collection, `^`, `CHR`, `DOT` of two lengths) carry none. The built-ins added for numerical work stay usable as names (a variable `E`, a `FUNCTION GCD`; `SOFT_BUILTINS` in `lang.ts`): a FUNCTION or PROCEDURE of the same name replaces the built-in, and a variable `E` is read as `E` while `E()` still calls the built-in.
|
|
||||||
|
|
||||||
`tests/numeric.test.mjs` pins each rule; the corpus programs `49-sized-integers` to `52-elementary` show them in use.
|
|
||||||
|
|
||||||
### Limits of a run
|
|
||||||
|
|
||||||
The reference's "Limits" and "What stops a run" tables (`src/common/reference.ts`) say the same to a student; `tests/reference.test.mjs` runs a program for every row of "What stops a run" (and fails on a row without one), and for five rows of "Limits": nesting, chains, a collection's size, steps and call depth.
|
|
||||||
|
|
||||||
- **What the parser reads.** A line inside more than 200 blocks, or brackets, calls, unary operators or types nested more than 200 deep, is one `too-deep` error (`MAX_NESTING` in `parse.ts`); so is a chain of more than 400 operands (`1 + 1 + ...`, `MAX_CHAIN`). The two are counted apart and a chain leans one level per operand, so brackets that each hold a long chain would multiply them; an expression whose tree is taller than 400 levels is therefore `too-deep` as well (`MAX_TREE`, measured where each expression is complete). No later stage (checker, analysis, translators) walks a taller tree; `tests/pseudo-robustness.test.mjs` takes the tallest through every one of them.
|
|
||||||
- **What a run holds.** One collection holds at most 2,000,000 values (an ARRAY's declared size, `FILL`, a range walked by `FOR EACH` or listed for a quantifier), and a text at most 10,000,000 characters (`MAX_VALUES`, `MAX_TEXT` in `interp.ts`); past either the run stops (kind `value`) instead of allocating.
|
|
||||||
- **How long a run goes.** The step limit (20,000 in the app's runs, `maxSteps`) stops a loop that may never end (kind `limit`). The positions FORALL, EXISTS, SUM and sets written by rule visit are counted apart, up to 100 per step allowed, so one quantifier inside another cannot run without end. Calls go 400 deep (`maxDepth`, kind `depth`); a recursion whose call sits inside many nested blocks can exhaust the engine underneath before 400 calls (with ten blocks around the call, somewhere between 200 and 300 calls, varying from run to run), which is the same stop, at the line the run was on.
|
|
||||||
- **The Prove tab's budget.** The verifier's work is counted, not timed (`work` in `logic.ts`): one obligation's proof, one subroutine's paths and invariants, its proofs, and the whole program each have a budget, the same on every machine, and past one the answer is open ("too large to prove here") or the subroutine partial, never proved ([limits.md](limits.md#proving-and-testing)). A wall-clock budget stays behind them as a last resort: `provePseudo` gives the verifier 3 seconds per unit, then tries generated inputs on each routine within a counted budget of steps and also for up to 3 seconds (`checkProperties` with `maxWork` and `budgetMs`): a slow routine is tried on fewer inputs, not waited for. The 3 seconds are the Prove tab's (`PROVE_BUDGET_MS`); a caller gives another with `provePseudo(parsed, { budgetMs })` or `Workspace.proofBudgetMs`, and the command line, `library-check` and the tests give none, so their answers do not depend on the machine ([limits.md](limits.md#proving-and-testing)). A report says which routines the clock stopped (`ProofReport.clock`, and `timedOut` and an `out-of-time` note on the unit).
|
|
||||||
- **Recording.** A recorded run (the stepper, the table of values) keeps a picture of the variables after every step, and a picture copies each variable the step changed. A large collection that changes at many steps is copied at each of them, so once the copies of a run come to more than 10,000,000 values (about 80 MB of numbers; `maxRecorded` in `interp.ts`), the trace ends with a step of kind `unrecorded` that says so, and the run goes on without recording: its output, result, stop and line counts are the whole run's. No program of the corpus, the exercises or the lessons comes near it (the largest copies about 42,000). `tests/pseudo-robustness.test.mjs` holds the cut with a small budget.
|
|
||||||
|
|
||||||
- **Checker errors and stops added in the 2026-11 audits** (each in `tests/pseudo-robustness.test.mjs`, `tests/numeric.test.mjs` or `tests/reference.test.mjs`): `too-deep` (the limits above), `literal-range` for a whole-number literal past 2^53 − 1 and a FLOAT or FLOAT32 literal past its largest value, `recursive-type`, `array-of-array`, `array-length` (an ARRAY given a LIST or ARRAY of another length, when both are written as numbers), `bad-member` (a SET of anything but single values). Stops: the collection and text caps, the quantifier positions, an ARRAY given a value of another length at a store, a call or a RETURN, a FOR counter declared with a sized type leaving its type, a partial sum or product of `SUM_OF` or `DOT` past 2^53 − 1, `CHR` of a surrogate half, `TO_FLOAT` or `INPUT` of text that is not a decimal number, and NaN or an infinity passed to a FLOAT parameter from outside without `USE IEEE`.
|
|
||||||
|
|
||||||
### Soundness
|
### Soundness
|
||||||
|
|
||||||
A "proved" must be a proof. Two test files hold the prover to that, and a change to `logic.ts`, `solver.ts` or `vcgen.ts` must keep both green:
|
A "proved" must be a proof. Two test files hold the prover to that, and a change to `logic.ts`, `solver.ts` or `vcgen.ts` must keep both green:
|
||||||
|
|
||||||
- `tests/prover-soundness.test.mjs`: every regression program in `library/pseudo/prover/` names, in a `// MUST-NOT-PROVE: <kind>@<line>` header, an obligation that a run breaks and that an unsound rule once proved; it may never be proved again, and the program must still break it. A program whose fix was to the language names where its run now stops, `// RUN-STOPS: <kind>@<line>`. Across every exercise, corpus program, lesson solution and example, nothing marked proved may be broken by the fuzzer or by running the program, and `ASSERT 1 == 2` appended to a program that runs to its end may never be proved.
|
- `tests/prover-soundness.test.mjs`: every regression program in `tests/prover/` names, in a `// MUST-NOT-PROVE: <kind>@<line>` header, an obligation that a run breaks and that an unsound rule once proved; it may never be proved again, and the program must still break it. A program whose fix was to the language names where its run now stops, `// RUN-STOPS: <kind>@<line>`. Across every exercise, corpus program, lesson solution and example, nothing marked proved may be broken by the fuzzer or by running the program, and `ASSERT 1 == 2` appended to a program that runs to its end may never be proved.
|
||||||
- `tests/engine-solver.test.mjs`: a table of goals the solver must prove and goals it must leave unknown, 400 random linear integer formulas checked against every small assignment, and obligations from small programs.
|
- `tests/engine-solver.test.mjs`: a table of goals the solver must prove and goals it must leave unknown, 400 random linear integer formulas checked against every small assignment, and obligations from small programs.
|
||||||
|
|
||||||
Those hold what someone wrote down. `pixi run prove-fuzz` ([scripts/prove-fuzz.mjs](../scripts/prove-fuzz.mjs)) writes programs nobody did: procedures with contracts, loops with INVARIANTs (FOR, WHILE, FOR EACH, REPEAT), STEPs that are expressions, CASE, FLOAT, FLOAT32 and sized types, calls on the right of AND and OR, and FUNCTIONs that draw a random number or read INPUT. Each is proved, then run on random arguments; a proved obligation a run breaks is a finding, printed as the smallest program that still shows it (`--keep DIR` writes it with its `// MUST-NOT-PROVE:` header, ready for `library/pseudo/prover/`). CI runs it on every push and longer every night ([ci.md](ci.md)).
|
When a soundness bug is found, add the program that shows it to `tests/prover/` first, watch the test fail, then fix the rule. The bugs found so far, each with its program:
|
||||||
|
|
||||||
When a soundness bug is found, add the program that shows it to `library/pseudo/prover/` first, watch the test fail, then fix the rule. The bugs found so far, each with its program:
|
|
||||||
|
|
||||||
| Program | Rule | Fix |
|
| Program | Rule | Fix |
|
||||||
|---|---|---|
|
|---|---|---|
|
||||||
@@ -69,47 +36,17 @@ When a soundness bug is found, add the program that shows it to `library/pseudo/
|
|||||||
| `fill-negative.pseudo`, `randint-empty.pseudo` | `FILL` and `RANDINT` assumed facts about arguments the interpreter checks by stopping, without asking whether they hold | An `argument` obligation, and guarded facts |
|
| `fill-negative.pseudo`, `randint-empty.pseudo` | `FILL` and `RANDINT` assumed facts about arguments the interpreter checks by stopping, without asking whether they hold | An `argument` obligation, and guarded facts |
|
||||||
| `float-overflow.pseudo` | The prover treats FLOAT as numbers (`Y == Y`), while a run went on with infinity and NaN | The interpreter stops on a FLOAT that is not finite |
|
| `float-overflow.pseudo` | The prover treats FLOAT as numbers (`Y == Y`), while a run went on with infinity and NaN | The interpreter stops on a FLOAT that is not finite |
|
||||||
| `foreach-empty.pseudo` | The way out of `FOR EACH` kept "X is in the collection", false after zero passes over an empty list | The fact holds only inside a pass |
|
| `foreach-empty.pseudo` | The way out of `FOR EACH` kept "X is in the collection", false after zero passes over an empty list | The fact holds only inside a pass |
|
||||||
| `int8-overflow.pseudo` | (a guard written with the sized types) Sized arithmetic treated as exact with no range would prove `X + 1` fits INT8 | Every sized result has an `overflow` obligation |
|
|
||||||
| `float32-store.pseudo` | (a guard) A whole number stored in a FLOAT32 keeping its exact value would prove `X == N` for N = 16777217 | A value becoming a FLOAT32 is rounded (constants) or `TOFLOAT32(v)` |
|
|
||||||
| `ieee-nan.pseudo` | (a guard) `X == X` for every number fails for NaN | Nothing is proved in a program that says `USE IEEE` |
|
|
||||||
| `havoc-float-sort.pseudo` | At the top of a loop a changed variable became an unknown of the sort its value had, so a FLOAT that started at `1` was a whole number on every pass | The unknown has the sort of the variable's declared type |
|
|
||||||
| `havoc-array-length.pseudo` | "An ARRAY keeps its dimensions through a loop" was assumed even when the body replaces the array whole (`A <- B`) | Assumed only when the body never assigns, declares or passes BYREF the bare name; and an ARRAY keeps its declared length: a store, an argument (BYREF too), a RETURN or a value APPENDed to a LIST OF ARRAY of another length is a checker error (`array-length`) when both lengths are plain numbers, and otherwise stops the run, where the prover asks for it (an `argument` obligation) and knows it afterwards; an ARRAY parameter's lengths are known inside the routine |
|
|
||||||
| `shortcircuit-range.pseudo`, `shortcircuit-ensure.pseudo`, `case-label-ensure.pseudo` | A fact learned while translating an expression (a sized result's range, a callee's ENSURE) was kept even where a short-circuit `AND`/`OR` or an earlier CASE label means the run never evaluates it | Such a fact is guarded by the conditions under which the expression is evaluated (`learn`) |
|
|
||||||
| `quantifier-ensure.pseudo` | The ENSURE of a call inside a quantifier's body was kept as a fact about the quantifier's own name, one free name shared by every quantifier | No ENSURE is stated for a call inside a quantifier's body |
|
|
||||||
| `impure-function.pseudo`, `input-function.pseudo`, `randn-twice.pseudo` | Every FUNCTION call, and `RANDN()`, was a function of its arguments, so two calls were equal | A function that reads INPUT or draws a random number (itself or through a call) gives a fresh unknown each call, with its ENSUREs; so does `RANDN()` |
|
|
||||||
| `rand-in-set-builder.pseudo` | A random draw in a quantifier's or set builder's body was one unknown for every value of its name | A body that draws makes the whole quantifier an unknown |
|
|
||||||
| `foreach-invariant-exit.pseudo`, `foreach-invariant-next.pseudo` | FOR EACH assumed its INVARIANT on the way out, where no run checked it, and proved "kept" for the value just visited while the run checked with the next | An INVARIANT that does not name the loop's variable is checked by the run once more when the loop ends (also for an empty collection) and is known afterwards; one that names it is proved for the value about to be visited and is not known afterwards |
|
|
||||||
| `repeat-invariant-exit.pseudo` | The run checks a REPEAT loop's INVARIANT after the last pass; "kept" covered only passes that repeat | The keep obligation covers the pass that ends the loop too |
|
|
||||||
| `step-not-literal.pseudo` | A FOR whose STEP is not a plain number was advanced by 1 | Its counter is an unknown after each pass, and inference offers nothing about it |
|
|
||||||
| `decreases-recursion.pseudo` | A recursive call's measure was compared with the parameters as they are at the call, not as they were on entry (what the run compares with) | Compared with the values on entry |
|
|
||||||
| `decreases-entry.pseudo` | The run checks `DECREASES >= 0` on every call; nothing asked for it | A `decreases-bound` obligation at the DECREASES line, from the REQUIREs |
|
|
||||||
| `sum-float-rounding.pseudo` | SUM over one more position was the exact sum, for FLOAT too | A FLOAT SUM grows by the uninterpreted `FLOAT+` |
|
|
||||||
| `sum-past-exact.pseudo`, `sum-not-finite.pseudo` | (a run that went on) SUM was not checked as `+` is: a whole number past 2^53 - 1 or an infinity went on, and two infinities made NaN | Every partial sum is checked; the run stops |
|
|
||||||
| `linear-doubles.pseudo`, `constant-doubles.pseudo`, `for-bound-doubles.pseudo` | Constants and coefficients were added and multiplied as doubles, so `9007199254740991 + 2 - 9007199254740991` was 1 | `linear()` works in exact rationals (`Q`, now in `logic.ts`), and constants fold only when both and the result are whole numbers a double holds exactly |
|
|
||||||
| `input-past-exact.pseudo` | (a run that went on) INPUT, `TO_INTEGER` and a FOR counter let a whole number past 2^53 - 1 into a run, where DIV and MOD are no longer exact | The run stops, as it does for `+` |
|
|
||||||
| `index-of-empty.pseudo` | `INDEX_OF` assumed a result below the length; an empty piece is found at 0 in an empty text | The fact allows 0 |
|
|
||||||
| `chr-surrogate.pseudo` | (a run that went on) `CHR` gave the halves of a surrogate pair, two CHARs that joined into one character | `CHR` stops for 0xD800 to 0xDFFF |
|
|
||||||
| `float-in-range.pseudo` | `X IN [lo, hi)` and membership of a set written by rule were `lo <= X < hi` for a FLOAT too; in a run only a whole number is in a range | Left open (an opaque term) unless X is a whole number |
|
|
||||||
| `set-literal-mixed.pseudo` | `{1, 2.5}` was a SET OF INTEGER holding 2.5 | A set literal widens to FLOAT, as a list literal does (`check.ts`) |
|
|
||||||
| `max-float32.pseudo`, `append-float32.pseudo` | A FLOAT32-typed value that was never rounded (MAX of a FLOAT32 and an INTEGER; APPEND of an INTEGER into a LIST OF FLOAT32) was taken for a FLOAT32 | MIN, MAX and CLAMP round a FLOAT32 answer, APPEND and INSERT store a value as the list's own type (and check a sized whole number), on both sides |
|
|
||||||
| `set-of-lists.pseudo` (removed) | A run's SET finds a LIST by identity; the prover compared contents | Membership of a collection in a SET was left open; then a SET's members were limited to the single values a HASHMAP key may be (checker error `bad-member`), so the program no longer checks and `tests/pseudo-robustness.test.mjs` holds the error instead |
|
|
||||||
| `sorted-2d.pseudo` | `SORTED` of a two-dimensional ARRAY has rows times columns values; the prover gave it the first length | Nothing is said about its length |
|
|
||||||
| `for-sized-counter.pseudo` | The run checks at the top of each pass that a FOR counter declared with a sized type (`DECLARE I : INT8`) still fits it, and stops there; no obligation asked, so a unit with everything proved still stopped | An `overflow` obligation at the FOR line, under the loop's guard, after which the range is a fact |
|
|
||||||
|
|
||||||
Fixes with no program of their own, because the program that showed them is now rejected or no longer breaks (each has a test in `tests/numeric.test.mjs`): `CLAMP(I, 0.5, 2.5)` was typed INTEGER and is now the widest of its three types; `UPPER`/`LOWER` of a CHAR whose other case is two characters (`'ß'`) leaves it as it is, so a CHAR is always one character; `RAND(X)` no longer returns X itself for the smallest FLOATs; an ARRAY or HASHMAP given as an argument from outside is checked value by value; INPUT into a FLOAT takes a finite number only (unless `USE IEEE`).
|
In the app, an obligation the prover marks proved that a generated input breaks at the same place is shown as broken, not proved.
|
||||||
|
|
||||||
The harness reads a regression program's `// INPUT: <line>` headers (one per line of input) and `// CALL: <call>`. A program may carry both a `MUST-NOT-PROVE` and a `RUN-STOPS` header when the run reports the failure on another line than the obligation's (a recursive DECREASES is reported at the DECREASES line, its obligation sits at the call).
|
|
||||||
|
|
||||||
In the app, an obligation the prover marks proved that a generated input breaks at the same place is shown as broken, not proved. A failure that says which half of a contract it broke (an INVARIANT before the first pass or after one, a DECREASES below 0 or not smaller) counts against that obligation only.
|
|
||||||
|
|
||||||
## What this repository changed
|
## What this repository changed
|
||||||
|
|
||||||
Changes made here since the engines left the course, which the course receives with the next export:
|
Changes made here since the engines left the course, which the course receives with the next export:
|
||||||
|
|
||||||
- **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; `coach.js` no longer warning "growing bound" on a queue drained by `WHILE LENGTH(Q) > 0`; the soundness fixes above, with the new `argument` obligation kind (`vcgen`, and `views-analysis.js` for the course's pages); a run that stops on a FLOAT that is not finite (`interp`); the sized types, FLOAT32, `USE IEEE` and the exact numerical built-ins (`numeric`, new, and `lang`, `parse`, `check`, `interp`, `vcgen`); `USE` of the library's routines by name (`parse`, `check`, `interp`); the limits of what the parser reads and a run holds, the recording cut, and the checker errors and stops of the 2026-11 audits (above); the prover's counted budgets (`work` in `logic`); a FUNCTION in an IF, WHILE or UNTIL condition run once per test (`interp`); and `logic`, `solver`, `vcgen`, `lang`, `numeric`, `parse`, `check` and `interp` rewritten in TypeScript with the same behavior, on the types in `ast.ts`.
|
- **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; `coach.js` no longer warning "growing bound" on a queue drained by `WHILE LENGTH(Q) > 0`; the soundness fixes above, with the new `argument` obligation kind (`vcgen`, and `views-analysis.js` for the course's pages); a run that stops on a FLOAT that is not finite (`interp`); and `logic`, `solver` and `vcgen` rewritten in TypeScript with the same behavior.
|
||||||
- **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; a limit on the memory a setup names (a region of at most 1 MiB) and on what a run's writes copy (128 MiB), in `interp.js`; 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.
|
- **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 steps of its own: before the parse it stops reading past 2,000 lines or 100,000 characters (`too-long`), and between parse and check it puts in the starting values and brings in the routines a `USE` line names. For the starting value, 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. It can move into the engine's parser now that the engine lives here.
|
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. It can move into the engine's parser now that the engine lives here.
|
||||||
|
|
||||||
## Giving the course the engines
|
## Giving the course the engines
|
||||||
|
|
||||||
|
|||||||
+6
-6
@@ -1,25 +1,25 @@
|
|||||||
# Adding an exercise
|
# Adding an exercise
|
||||||
|
|
||||||
Programming+ takes a procedure from an idea to Mojo to the machine. An exercise is one procedure on that road, written in any of its notations: lingo (steps in plain English), matho (equations written in LaTeX), pseudo (pseudocode precise enough to run, prove and translate), speco (a specification to prove against), Mojo (Modular's programming language, pinned to version 1.2.0) and x86-64. It 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.
|
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.
|
There are two ways to start one.
|
||||||
|
|
||||||
## An exercise around a Mojo program
|
## An exercise around a Mojo program
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
pixi run new-exercise rolling-sum # library/mojo/local/rolling-sum.mojo, src/exercises/rolling-sum.ts, registered
|
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
|
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 `library/mojo/local/rolling-sum.mojo` already exists, it is kept as written and only the exercise is made.
|
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.2.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).
|
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)).
|
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
|
## 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 `demo`, the playground, which stays last). Then `pixi run test`.
|
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
|
## The fields
|
||||||
|
|
||||||
@@ -29,7 +29,7 @@ Copy `src/exercises/_template.ts` to `<id>.ts`, fill it in, import it in `src/ex
|
|||||||
| `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 |
|
| `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) |
|
| `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 |
|
| `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 `library/mojo/local/`, shown in the Mojo pane |
|
| `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 |
|
| `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 |
|
| `setup`, `machine` | For assembly: the setup block (registers and memory before the run) and the machine model preset |
|
||||||
| `lang` | The pane that opens first |
|
| `lang` | The pane that opens first |
|
||||||
|
|||||||
@@ -1,43 +0,0 @@
|
|||||||
# The library
|
|
||||||
|
|
||||||
Programming+ takes a procedure from an idea to Mojo to the machine. pplus-library (the submodule `library/`) is its ground truth. Its routines, which this document is about, are written once in pseudo (pseudocode precise enough to run, prove and translate); besides them it holds the Mojo corpus (`library/mojo/`, see [mojo-corpus.md](mojo-corpus.md)) and the pseudo regression and soundness programs (`library/pseudo/`). Each routine is checked by every tool `pixi run library-check` has (the table below), so a program can use them by name instead of rewriting and re-verifying them, and a learner can open any of them to see exactly what it does. Core reads it through a generated registry (`src/library/generated.ts`, `pixi run library-emit`), so the site needs no files at run time.
|
|
||||||
|
|
||||||
## Using a routine
|
|
||||||
|
|
||||||
```
|
|
||||||
USE md // every routine of the module
|
|
||||||
USE align.MatchScore // one routine
|
|
||||||
```
|
|
||||||
|
|
||||||
USE lines go at the top of a program. From then on a routine is called like the program's own:
|
|
||||||
|
|
||||||
- **The checker** types each call against the routine's parameters. A program may not define a routine of the same name (`library-clash`); an unknown module or routine is an error at the USE line, with the names that exist (`unknown-library`, `unknown-routine`).
|
|
||||||
- **A run** steps over a routine: one step where it is called, one where it hands back, and none of its own lines (they belong to another file). Its contracts are still checked; a broken REQUIRE is reported at the call, naming the routine. To step through a routine, open it from the site's library page, which opens it in the Bridge.
|
|
||||||
- **The prover** uses the routine's REQUIRE as an obligation at each call and its ENSURE as a fact afterwards, the way it treats the program's own routines. It does not prove the routine again: the library did.
|
|
||||||
- **The Mojo translator** writes each routine the program uses once, before the program's own code, dependencies first, labeled as coming from the library.
|
|
||||||
|
|
||||||
A routine file (`routine.pseudo`) holds USE lines and exactly one FUNCTION or PROCEDURE. A routine that calls another brings it in with USE, so every function in the library is checked on its own.
|
|
||||||
|
|
||||||
## What "verified" means for a routine
|
|
||||||
|
|
||||||
`pixi run library-check` runs every check and records what it found in `library/status.json` and `library/STATUS.md`:
|
|
||||||
|
|
||||||
| Check | Passes when | Recorded as |
|
|
||||||
|---|---|---|
|
|
||||||
| structure | `routine.pseudo` defines exactly the routine `routine.json` names, and nothing else | pass, fail |
|
|
||||||
| pseudo | every case runs; its result is recorded and is what the references are held to | pass, fail |
|
|
||||||
| prover | every obligation of the routine is proved | pass; open (some not proved, none broken: the routine's comment says which and why, and `tests/documents.test.mjs` fails when it does not mention it); fail (one broken) |
|
|
||||||
| fuzz | every input the fuzzer generates for the routine breaks no contract and stops no run (`STATUS.md` gives how many it generated) | pass, fail, skipped (the fuzzer cannot generate inputs for it) |
|
|
||||||
| mojo | the Mojo generated from the pseudo checks, and prints what the pseudo prints both in core's interpreter and built by the pinned compiler on this machine (to the last digits or nearly: [trust.md](trust.md#what-a-translation-says)) | pass (by both, or by the one that could run it), fail, skipped (the interpreter declines the construct and there is no pinned compiler here) |
|
|
||||||
| a reference, per runner | `cpython`, `cc -O0`, `cc -O2`, core's Mojo `interpreter`, the pinned Mojo `compiler` on this machine, or the pinned compiler on `godbolt` prints the pseudo's results on every case, exactly or within the tolerance `routine.json` states; a C or Mojo reference is given its cases at run time (below) | pass, fail, skipped (the tool is missing, or the `mojo` on the PATH is not the pinned version), unverified (no stored compiler answer for this exact program, input and build arguments) |
|
|
||||||
| proof | the pinned Dafny verifies the proof file, or its stored verdict matches this exact text | pass, fail, unverified |
|
|
||||||
|
|
||||||
A reference implementation is the function alone; the tool writes the program it runs as (the function plus a main that prints each case), and `pixi run library-harness <id> <lang> <level>` prints it. A Python reference's program calls it on each case's arguments. A Mojo or C reference's program holds no case: its main reads every case's arguments from one line of stdin, which `pixi run library-harness-input <id> <lang> <level>` prints, so the compiler cannot work a call out while it builds (a call on literal arguments it would, with arithmetic and a math library of its own; built with contraction on, as Mojo is by default, with other rounding than the code it makes: `library/mojo/probes/float-contract-runtime`), and every runner is given the same program and the same line. Every Mojo program is built with the pin's arguments (`build.args` in `library/mojo/pin.json`: `--target-cpu x86-64-v3 --fp-mode contract=off`, [mojo-corpus.md](mojo-corpus.md#how-every-program-is-built)), on godbolt and on this machine, so a Mojo reference rounds each Float64 operation on its own, as the pseudo does. The line is the number of cases, each case's arguments, then `end`; a FLOAT is sent as two whole numbers m and e with the value m * 2^e, exactly, a STRING with `%`, space and line breaks escaped, a LIST as its length and then its items. `tests/library-harness.test.mjs` fails if a case's arguments are ever written into the program again. A Mojo reference's answer from the compiler is stored in the routine's `golden/mojo-<level>.json`, keyed by the SHA-256 of that program, the stdin it was given and the build arguments, by `pixi run library-verify-mojo` (network). A Dafny verdict is stored in `golden/dafny.json`, keyed by the proof's text and the Dafny version.
|
|
||||||
|
|
||||||
What each check does not say is in [trust.md](trust.md#library-routines).
|
|
||||||
|
|
||||||
## Changing the library
|
|
||||||
|
|
||||||
1. Change pplus-library under its [AGENTS.md](../library/AGENTS.md): one routine per file, cases, references with their notes and tolerances, a Dafny proof where one says something.
|
|
||||||
2. In core: `pixi run library-check` (no check may fail), then `pixi run library-emit`.
|
|
||||||
3. Commit pplus-library; commit core with the new `library` pointer and the regenerated registry. `tests/library.test.mjs` fails while the registry is out of date with the checkout.
|
|
||||||
@@ -1,84 +0,0 @@
|
|||||||
# Limits
|
|
||||||
|
|
||||||
A program can arrive in a share link, so every reader and every run in core has to answer any text with diagnostics, an output, a stop or a refusal: never with an exception from the JavaScript engine underneath, a run without end, or an allocation the size of the text's mistake. This page lists each limit that makes that so: where it is, its value, and what the student sees past it. Each is far beyond what a program written to be read or stepped through needs, and each is proven just past its value by a test.
|
|
||||||
|
|
||||||
## Reading
|
|
||||||
|
|
||||||
| What | Where | Value | Past it |
|
|
||||||
|---|---|---|---|
|
|
||||||
| Mojo nesting: brackets, call and index arguments, blocks, prefix operators, `**`, `if`/`else`, `:=`, lambdas | `MAX_NESTING`, `src/mojo/parse.ts` | 200 levels | The statement is not read: one note, "nested more than 200 levels deep; Programming+ cannot read this yet, and Compile & run asks the real compiler", where the limit is passed. The checks stay quiet and a run is declined, as for any code the parser cannot read |
|
|
||||||
| Mojo tree height: each operand of a chain such as `a + b + c`, each `elif` arm, each level above | `MAX_TREE`, `src/mojo/parse.ts` | 1,000 levels | The statement (the innermost one that is too tall) is not read: one note, "more than 1000 levels deep once read" |
|
|
||||||
| Mojo liveness and moved-value analyses (a loop's body is walked twice or more per enclosing loop) | `MAX_VISITS`, `src/mojo/lifetimes.ts`, `src/mojo/flow.ts` | 200,000 statements per function | The function is not analyzed: the interpreter declines to say when a value with a visible lifecycle dies, and the moved-value check says nothing more about it |
|
|
||||||
| Generated inputs for Mojo functions (`mojoProperties`) | `MAX_PARAMS`, `MAX_FUNCTIONS`, `src/mojo/properties.ts` | 64 parameters, the first 100 functions | The report says the function has too many parameters, or is past the first 100 |
|
|
||||||
| Pseudo nesting, one chain of an operator, and the tree both make together | `MAX_NESTING`, `MAX_CHAIN`, `MAX_TREE`, `src/engines/pseudo/parse.ts` | 200 levels, 400 operands, and an expression's tree 400 levels tall (brackets that each hold a long chain) | One `too-deep` error |
|
|
||||||
| One pseudocode program (the pseudo pane, and the pseudocode any other pane becomes) | `MAX_PSEUDO_LINES`, `MAX_PSEUDO_CHARS`, `src/services/pseudo-study.ts` | 2,000 lines, 100,000 characters | One `too-long` error on the line that passes it: "This program is more than 2,000 lines long" (or "longer than 100,000 characters"), "which is more than this tool reads: the lines from here on are not read, and the program is not run or proved." Blank lines past it do not count |
|
|
||||||
| lingo nesting: brackets, "not", "minus", quantifiers, steps inside steps | `MAX_NESTING`, `src/engines/pseudo/english.js` | 200 levels | One `too-deep` error: "This is nested more than 200 levels deep, which is more than this tool reads" |
|
|
||||||
| One lingo sentence | `MAX_SENTENCE`, `src/engines/pseudo/english.js` | 1,000 words and symbols | One `too-long` error; the rest of the sentence is not read |
|
|
||||||
| lingo routines and defined phrases (every value is tried against each one's first line) | `MAX_HEADS`, `src/engines/pseudo/english.js` | 200 | One `too-long` error; the ones past it are not read |
|
|
||||||
| One lingo program | `MAX_PSEUDO_LINES`, `src/engines/pseudo/english.js` | 2,000 lines | One `too-long` error; the lines past it are not read |
|
|
||||||
| The pseudocode lingo steps become | `MAX_PSEUDO_LINES`, `src/engines/pseudo/english.js` | 2,000 lines | One `too-long` error; it is not checked or run |
|
|
||||||
| matho nesting: brackets, groups, `\frac`, `\sqrt`, powers and subscripts in braces, functions of functions, signs | `MAX_NESTING`, `src/services/matho.ts` | 200 levels | `matho-too-deep` on that equation |
|
|
||||||
| One matho equation | `MAX_TOKENS`, `src/services/matho.ts` | 2,000 symbols | `matho-too-long` on that equation; it is not read |
|
|
||||||
| Equations in one matho pane | `MAX_EQUATIONS`, `src/services/matho.ts` | 500 | `matho-too-long`; none is read |
|
|
||||||
| The pseudocode matho equations become | `MAX_PSEUDO_LINES`, `src/services/matho.ts` | 2,000 lines | `matho-too-long`; it is not checked or run |
|
|
||||||
| `LENGTH(X)` written back as `\|X\|` when the speco is made from the pseudocode | `MAX_BARS`, `src/services/speco.ts` | 200 per claim | The rest stay `LENGTH(X)` |
|
|
||||||
| A reader, translator or the prover that throws anyway | `src/common/workspace.ts`, `src/sync/hub.ts` | | One `engine-stop` error on the pane ("Programming+ could not read this pane (...)"); in the hub, every other pane keeps its text, marked stale with the reason |
|
|
||||||
|
|
||||||
## Running Mojo
|
|
||||||
|
|
||||||
Past any of these the run stops as it does at its step limit: the trace ends with a stop at the line, and the result is `limited` (exit code -1), because how the compiled program would have ended is not known (`RUN_LIMITS`, `src/mojo/interp.ts`; a run may ask for lower limits, never higher).
|
|
||||||
|
|
||||||
| What | Value | The stop says |
|
|
||||||
|---|---|---|
|
|
||||||
| Steps | 20,000 (the caller's `maxSteps`) | "Stopped after 20,000 steps." |
|
|
||||||
| Calls inside calls | 200 | "Stopped at 200 calls deep" |
|
|
||||||
| Characters in one String | 10,000,000 | "Stopped: this makes a String of N characters, more than Programming+ holds (10,000,000)." |
|
|
||||||
| Values in one List, Dict or Set | 2,000,000 | "Stopped: this makes a List of N values, more than Programming+ holds (2,000,000)." |
|
|
||||||
| Characters printed | 10,000,000 | "Stopped after printing 10,000,000 characters." |
|
|
||||||
| Values made or copied into collections, over the run (what it can come to hold) | 5,000,000 | "Stopped after making or copying 5,000,000 values in Lists, Dicts and Sets" |
|
|
||||||
| Characters and values built, copied or searched through, over the run (how long it can take; the whole length of a concatenation counts, because the trace keeps every step's String) | 100,000,000 | "Stopped after building, copying and searching through 100,000,000 characters and values" |
|
|
||||||
| Variables' values the trace records, one per variable per step | 1,000,000 | "Stopped after recording 1,000,000 values of variables" |
|
|
||||||
| Passes of one call of std.math's `gcd` or `comb` (`MATH_STEPS`), which the interpreter runs as Mojo 1.2.0's own loops: its `gcd` of an even number and a much larger odd one subtracts about 10^15 times, and the built program does not come back | 1,000,000 | "Stopped: gcd(6, 4503599627370597) takes more than 1,000,000 steps in Mojo's std.math ..., more than Programming+ follows in one call." |
|
|
||||||
| The engine's own stack or size limit, past all of the above | | "Stopped: the run went deeper ... than Programming+ can follow." or "Stopped: a value grew larger than Programming+ can hold." |
|
|
||||||
|
|
||||||
A `for` loop lists only the items it can reach before the step limit. The trace shows a String past 1,000 characters and a collection past 20 items cut short; `print` writes them whole. What the engine underneath cannot compute is declined, as anything the interpreter does not model is ("Programming+ cannot run this yet: ..."): a shift by more than 64 bits, converting `inf` or `nan` to an integer, a float literal with more than 10,000 digits or an exponent past 10,000, and any other exception, which is a fault in Programming+ rather than an answer.
|
|
||||||
|
|
||||||
## The model machine
|
|
||||||
|
|
||||||
| What | Where | Value | Past it |
|
|
||||||
|---|---|---|---|
|
|
||||||
| Steps | `maxSteps`, `src/engines/asm86/interp.js` | 20,000 | The run is truncated |
|
|
||||||
| One memory region a setup maps | `MAX_REGION` | 1 MiB | The run does not start: "this machine maps regions of 0 to 1,048,576 bytes (1 MiB)" |
|
|
||||||
| Memory copied while writing (each step that writes a region keeps a copy for stepping back) | `MAX_COPIED` | 128 MiB | The run stops: "the steps so far wrote to memory regions totaling 128 MiB" |
|
|
||||||
| The stack | `stackSize` | 512 bytes | A page fault, explained as a stack overflow |
|
|
||||||
|
|
||||||
## Proving and testing
|
|
||||||
|
|
||||||
The prover's work is counted, not timed: each term it builds or visits, each case of a case split, each pair of constraints it combines, each fact it copies is a unit (`work` in `src/engines/pseudo/logic.ts`). A budget therefore runs out at the same point on every machine and in every test, and because the units are counted where memory is allocated, memory stays in proportion. Past a budget the answer is never "proved": an obligation is open with the reason "too large to prove here", or the subroutine is partial and says so (in the Prove tab a partial subroutine has nothing marked proved). Every program of the corpus takes far less than each budget, and proves the same as before they were added (`tests/prover-limits.test.mjs` proves each budget past its value).
|
|
||||||
|
|
||||||
| What | Where | Value | Past it |
|
|
||||||
|---|---|---|---|
|
|
||||||
| Proving one obligation | `PROVE_WORK`, `src/engines/pseudo/solver.ts` | 2,000,000 units | The obligation is open: "too large to prove here" |
|
|
||||||
| Following one subroutine's paths and finding its loops' invariants | `UNIT_WORK`, `src/engines/pseudo/vcgen.ts` | 40,000,000 units | The subroutine is partial, with the note "This subroutine is too large to prove here: the checker stopped before the end of it, so nothing in it is marked proved. Every run still checks it." |
|
|
||||||
| Proving one subroutine's obligations | `PROOF_WORK`, `src/engines/pseudo/vcgen.ts` | 20,000,000 units | Each obligation not yet proved is open: "too large to prove here" |
|
|
||||||
| Everything above, for a whole program | `PROGRAM_WORK`, `src/engines/pseudo/vcgen.ts` | 60,000,000 units | The subroutines after it are partial, with the same note |
|
|
||||||
| How deep a value the checker follows is (`T <- T + A[T] + ...` line after line builds one operation inside another) | `MAX_DEPTH`, `src/engines/pseudo/vcgen.ts` | 500 operations (the corpus's deepest: 18) | The value becomes one the checker knows nothing about, with the note "The value on line N is built from more than 500 operations one inside another, more than the checker follows: from there on it treats such a value as one it knows nothing about, so what depends on it stays open." The engine's own stack or size limit, past everything, is the same as running out of work: the unit is partial, or the obligation open, too large to prove here |
|
|
||||||
| A term's key, which finds equal terms (a term that shares its parts, such as nested `ABS`, is far longer written out) | `MAX_KEY`, `src/engines/pseudo/logic.ts` | 2,000 characters | The term is equal only to itself: the prover concludes less about it, never more |
|
|
||||||
| A fact or goal written out with an obligation | `SHOW_PARTS`, `src/engines/pseudo/logic.ts` | 1,000 parts | The rest is written "…" |
|
|
||||||
| The facts and goals one subroutine's report writes out | `SHOWN_CHARS`, `src/engines/pseudo/vcgen.ts` | 1,000,000 characters | Each further obligation shows its goal alone, cut at 400 characters |
|
|
||||||
| The hypotheses looked through for the facts shown with an obligation | `SHOWN_FROM`, `src/engines/pseudo/vcgen.ts` | the nearest 400 | The facts shown come from those |
|
|
||||||
| The generated inputs that cross-check a proof (`checkProperties`), counted in steps and positions visited by FORALL, EXISTS, SUM and sets written by rule | `CROSS_CHECK_ROUTINE`, `CROSS_CHECK_PROGRAM`, `src/services/pseudo.ts` | 600,000 for one routine, 1,200,000 for a program | No more inputs are tried (the routines after it, none): an obligation they would have shown broken stays open. A run cut short by the budget is not a failure |
|
|
||||||
| The sample runs that check the equations a matho pane is given give the pseudo's values | `READ_BACK_VISITS`, `src/sync/pseudo-to-matho.ts` | 100,000 quantifier positions a run | The run stops there, on both sides alike, and the check compares where they stopped |
|
|
||||||
| The fuzzer's inputs for one routine (the Tests view, `Workspace.fuzz`), counted the same way | `WORK_PER_INPUT`, `src/common/fuzz.ts` | 3,000 for each input the budget asks for: 900,000 at the default 300 | No more inputs are run, and the report's `problem` says "Stopped after N steps of work, all one routine's inputs may take here (M): the inputs listed were run, and no more." A failure found before is kept, shrunk as far as the work allowed |
|
|
||||||
| The routines of one program the fuzzer tests | `FUZZ_ROUTINES`, `src/common/workspace.ts` | the first 100 | A report with no cases: "Not tested: generated inputs cover the first 100 routines of a program, and this is routine N." |
|
|
||||||
| The fuzzer's work for a whole program | `FUZZ_PROGRAM_INPUTS`, `src/common/workspace.ts` | 600 inputs' worth: 1,800,000 at the default budget | A report with no cases: "Not tested: the routines before this one took all the work the tests of one program may take (1,800,000 steps)." |
|
|
||||||
|
|
||||||
The wall-clock budget the Prove tab gives each subroutine (3 seconds, `PROVE_BUDGET_MS` in `src/services/pseudo.ts`) stays behind these as a last resort. It is the caller's: `provePseudo` and `Workspace.proofBudgetMs` take another, and what has to say the same thing on every machine takes none (`pixi run cli prove` unless `--budget-ms` gives one, `library-check`, the tests), so the counted budgets decide alone. The clock is the one part of a proof that depends on the machine: on CI's runner, where the README's example took more than its 3 seconds (it takes 5 milliseconds on the machine this was written on), 4 of its 6 obligations stayed open. A slow or busy device shows the same in the Prove tab: fewer obligations proved, more open, none wrongly proved. The report says when that happened (`clock.stopped` names the routines: those the prover ran out of time on, each with `timedOut` and a note, and those whose generated inputs were cut short while a claim was still open), and the site lets the reader give the prover more time (its `docs/app.md`). Measured on the machine this was written on: 20 nested `ABS` (or a matho pane `f(x) = ||||...x...||||` of 20 bars) took a 1 GB heap down before, and now ends in 0.1 seconds in a 128 MB heap; a subroutine at `UNIT_WORK` takes 0.7 to 2 seconds, one at `PROOF_WORK` about 1 second, and a program at `PROGRAM_WORK` about 4 seconds, each in a 128 MB heap. The most any program of the corpus takes is 234,000 units for one obligation, 145,000 for one subroutine's paths, 783,000 for its proofs and 886,000 for the whole program. `prove-fuzz` makes larger programs than anyone writes: the most in seeds 9137 and 22051 (800 programs each) are 768,000, 35,000,000 (a subroutine its 1.5-second wall-clock budget had already cut short), 5,100,000 and 38,000,000, and the proved obligations of both seeds are the same with the budgets as without. The cross-check is counted the same way: one input of a routine whose ENSURE nests 8 quantifiers visited 5,000,000 positions (7 seconds) before, and the whole cross-check of a routine now takes at most about 2 seconds; the most any routine of the corpus takes is 347,000 (`match-off-by-one`). The fuzzer runs a routine's inputs within its budget in about a second, a program's in about 2 (a program of 2,000 small routines, the first 100 fuzzed: 2 seconds); the most the corpus takes is 400,000 for one routine (kmers' `kmer_counts` in Mojo), 1,300 for one input, and every corpus program's report is the same as before.
|
|
||||||
|
|
||||||
## What the compiler does
|
|
||||||
|
|
||||||
The checker may never report an error on a program the compiler accepts, so the Mojo limits are a refusal to read, not an error. Asked through `mojo build` at the pin (Mojo 1.2.0), the compiler accepts 5,000 nested parentheses, 5,000 nested calls, 1,000 nested blocks, 5,000 `elif` arms and a 10,000-term sum, and crashes (exit 139, a stack overflow in the compiler) on 30,000 nested parentheses, a 30,000-term sum, or 30,000 minus signs. There is no depth it refuses with an error message.
|
|
||||||
|
|
||||||
## The tests
|
|
||||||
|
|
||||||
`tests/mojo-robustness.test.mjs` proves the Mojo limits and `tests/reader-limits.test.mjs` the others, each just past its value with inputs small enough to keep the test quick, and each shape just under it still reading and running. `tests/pseudo-robustness.test.mjs` has the pseudocode's.
|
|
||||||
+26
-64
@@ -4,23 +4,21 @@ Programming+ teaches what Mojo does when it runs, so everything it says about Mo
|
|||||||
|
|
||||||
Every command below is a pixi task; the [README](../README.md#commands) lists them all.
|
Every command below is a pixi task; the [README](../README.md#commands) lists them all.
|
||||||
|
|
||||||
The corpus itself (the pin, the harvested material, our programs and godbolt's answers) lives in pplus-library, the submodule `library/`, under `library/mojo/`; the pipeline that builds and checks it (`scripts/mojo/`) and what it generates for the app (`src/mojo/generated/`) live here. A task that changes the corpus leaves changes in both repositories: commit and push `library/` first, then commit core with the new pointer (`git add library`) and the regenerated files.
|
|
||||||
|
|
||||||
## Mojo of our own
|
## 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:
|
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 |
|
| Kind | Folder | Start one | Its job | Shipped in the app |
|
||||||
|---|---|---|---|---|
|
|---|---|---|---|---|
|
||||||
| probe | `library/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 |
|
| 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 | `library/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 |
|
| 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 | `library/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 |
|
| 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:
|
The loop is the same for all three:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
pixi run new-probe int-floordiv-negative "does // floor toward negative infinity on Int?"
|
pixi run new-probe int-floordiv-negative "does // floor toward negative infinity on Int?"
|
||||||
# edit library/mojo/probes/int-floordiv-negative.mojo
|
# edit mojo/probes/int-floordiv-negative.mojo
|
||||||
pixi run mojo-verify-item 'probes/int-floordiv-negative' # ask godbolt (network)
|
pixi run mojo-verify-item 'probes/int-floordiv-negative' # ask godbolt (network)
|
||||||
pixi run test # the checker and interpreter scoreboards read the new answer
|
pixi run test # the checker and interpreter scoreboards read the new answer
|
||||||
```
|
```
|
||||||
@@ -35,7 +33,7 @@ A program starts with comment lines that `corpus.py verify` reads. Only these ke
|
|||||||
# probe: what does // do on negative Int? the question, or what the program shows (one line)
|
# 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
|
# stdin: 3\n4\n what input() reads, with \n escapes
|
||||||
# mode: run run | asm | both (asm and both also return the listing)
|
# mode: run run | asm | both (asm and both also return the listing)
|
||||||
# args: -O0 compiler arguments, after the pin's build arguments (below)
|
# args: -O0 compiler arguments
|
||||||
# expect-stdout: -4 a line the program must print (repeatable); implies expect: pass
|
# 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)
|
# expect: compile-error pass | fail | compile-error | observe (the default without expect-stdout)
|
||||||
# origin: where the program came from free text, for people
|
# origin: where the program came from free text, for people
|
||||||
@@ -44,17 +42,6 @@ A program starts with comment lines that `corpus.py verify` reads. Only these ke
|
|||||||
|
|
||||||
**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.
|
**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.
|
||||||
|
|
||||||
### How every program is built
|
|
||||||
|
|
||||||
Mojo is built one stated way everywhere core builds a program or asks godbolt to: `corpus.py verify`, `library-verify-mojo`, the Compile button (`BUILD_ARGS` in `src/services/godbolt.ts`: the pin's arguments, then the level's), `library-check`, `mojo-local`, `mojo-fuzz`, `mojo-run` and `play`. The arguments are `build.args` in `library/mojo/pin.json`, each with its reason under `build.why`:
|
|
||||||
|
|
||||||
- `--target-cpu x86-64-v3`. Without it `mojo build` targets the processor it runs on, and godbolt's machines differ: on 2026-11-12 every stored listing was AVX2 (`ymm`), and at 12:55 EST the same request for `local/demo` came back with AVX-512 (`zmm`, `kmovq`, `vpternlogd`), instructions the model machine does not know. x86-64-v3 is AVX2, FMA, BMI1 and BMI2, with no AVX-512, so a listing is the same whichever machine answers (`probes/godbolt-target-cpu`). A machine that is not x86-64 (an Apple silicon Mac) cannot build for it, so there the local tools leave it out.
|
|
||||||
- `--fp-mode contract=off`. Mojo's default, `contract=fast`, fuses a multiply with an add or subtract into one rounding wherever the operands arrive at run time: `probes/float-contract-runtime` (built with `contract=fast` on purpose) prints -0.22222222222222224 for `x * x - x` when `x` comes from stdin and -0.2222222222222222 when it is a literal the compiler works out while building. With contraction off every Float64 operation is rounded on its own, as IEEE 754 says and as the pseudo interpreter and core's Mojo interpreter compute (`probes/float-contract-runtime-off` prints -0.2222222222222222 twice).
|
|
||||||
|
|
||||||
A program's own `# args:` come after these, and an option it names replaces the pin's (the contraction probes name `--fp-mode` themselves). Every stored answer records the arguments it was built with (`args`) and is keyed by them, so a change to `build.args` leaves every answer unverified until `pixi run mojo-verify` and `library-verify-mojo` ask again. `tests/build-args.test.mjs` fails when a builder writes a code-generation flag of its own or the Python and TypeScript halves combine the arguments differently.
|
|
||||||
|
|
||||||
`mojo build` or `mojo run` on your own machine, without these arguments, targets your processor and fuses: its last digits and its listing can differ from what Programming+ shows. `pixi run mojo-run <file>` builds the way everything else does.
|
|
||||||
|
|
||||||
### The fast loop for an exercise program
|
### The fast loop for an exercise program
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
@@ -66,33 +53,13 @@ One pass is: run the file on the local `mojo` (pixi provides it); `corpus.py ver
|
|||||||
|
|
||||||
### The assembly
|
### The assembly
|
||||||
|
|
||||||
A program whose header says `# mode: both` (or `asm`) and `# args: -O0 --debug-level=line-tables` (after the pin's build arguments) 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 (the pin's and the program's) 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.
|
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.
|
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.
|
||||||
|
|
||||||
## The compiler on your machine
|
|
||||||
|
|
||||||
Godbolt's stored answers cover the programs someone wrote down, and they need the network. pixi also installs the pinned compiler, and two tasks hold core to it directly, offline:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
pixi run mojo-local # every Mojo program core holds or generates
|
|
||||||
pixi run mojo-fuzz --seed 7 --programs 50 # programs nobody wrote
|
|
||||||
pixi run mojo-fuzz --statements --seed 7 # whole programs of statements nobody wrote
|
|
||||||
```
|
|
||||||
|
|
||||||
`mojo-local` (`scripts/mojo/local.mjs`) builds and runs the probes, exercise programs and stress programs as written, the Mojo the translator writes for every exercise, every pseudo regression program and every library routine on its cases, and every Mojo reference of the library. For each it asks: does the checker stay silent on what the compiler accepts; does the interpreter print what the built program prints and end the same way, or decline; does the compiler accept generated Mojo, and does it print what the pseudo prints; does this compiler agree with godbolt's stored answer for the same text, arguments and stdin. Every "no" is printed, and the task fails. The differences that are right are listed in `EXPECTED` at the top of the script, each with its reason; a listed one that stops differing fails the pass too, so the list only shrinks. Answers are cached in `.tools/mojo-local/` by compiler version, arguments, stdin and source.
|
|
||||||
|
|
||||||
`mojo-fuzz` (`scripts/mojo/fuzz.mjs`) writes typed pseudo expressions at random from the notation's operators and built-ins, one per OUTPUT line, drops the lines the pseudo itself stops on or refuses, translates the rest, builds them, and holds each printed line to the pseudo's. It reports a line the compiler rejects, a line where the built program stops, a line that prints another value, a line where the interpreter prints something else than the built program, and a checker error on an accepted program, once per shape with the smallest expression that shows it. The same seed gives the same programs. Run it with a few seeds after changing `src/sync/pseudo-to-mojo.ts` or `src/mojo/`; when it finds something, fix the rule and pin the spelling in `tests/sync-mojo.test.mjs`.
|
|
||||||
|
|
||||||
With `--statements` it writes whole programs instead (20 to 60 lines, 100 per seed by default; the generator is `scripts/mojo/fuzz-programs.mjs`): records, constants, FUNCTIONs and PROCEDUREs with by-value and BYREF parameters of scalars and collections, some recursive with a bound, then the main lines, built from DECLARE of every scalar, sized, collection and record type, assignment to names, elements, fields and map entries, IF and CASE, FOR with positive and negative steps, FOR EACH over lists, arrays, text, ranges, maps and sets, WHILE, REPEAT, BREAK and CONTINUE, the collection built-ins, copies changed after they are made, and a tagged OUTPUT at many points, so the first line that differs says where. The generator is typed, so most programs check as written; the pseudo's checker and a run are the filter, and a line the checker refuses, a run stops on, or the translator says it has no Mojo for is left out and the rest tried again. A program whose output changes when SET members and map keys are visited in another order is dropped, since the notation never promised an order. The report says how many programs settled, which constructs they held, every finding once per shape with its smallest program, shrunk by leaving out statements one at a time while the built program still shows the same finding (`--shrink N` builds at most, 80 by default), and the pseudo engine's own faults apart. `--progress` prints each finding as it is found; `--dry` only generates and settles, to measure the generator.
|
|
||||||
|
|
||||||
Two kinds of difference are counted and not reported as failures, because the compiler decides them ([trust.md](trust.md#what-a-translation-says)): numbers that differ only in their last digits (the compiled program's `std.math` is its own; its arithmetic is the pseudo's, since every program is built with contraction off), and, for lines that use `**`, `exp` or `log2`, what those lose in Mojo 1.2.0 (they are good to 9 to 13 digits). What the compiler does wrong on its own is listed in `UPSTREAM` in the fuzzer, with the probe that records it; read that list on every version bump.
|
|
||||||
|
|
||||||
Neither task needs or replaces godbolt. Both need a C compiler: `mojo build` compiles a program and has the `gcc` or `cc` it finds link it, against a C library no older than glibc 2.34. The pinned environment brings one on Linux (`pixi.toml`), so under `pixi run` the system's is not used; a program that compiles and cannot be linked is reported by `mojo-local` as not linked, the machine's fault and not Mojo's answer, and is not kept in its cache. A built program that traps is run with its core-dump limit set to 1, so a deliberate crash does not reach the desktop's crash handler. CI runs both in the pinned environment, which brings the compiler: `pixi run ci` runs `mojo-local` and a short `mojo-fuzz`, and the nightly run fuzzes longer ([ci.md](ci.md)). Run both yourself after changing the translator, the checker or the interpreter, and after a version bump.
|
|
||||||
|
|
||||||
## Reading the status
|
## Reading the status
|
||||||
|
|
||||||
`pixi run mojo-status` judges every item from the stored answers, offline, and writes `library/mojo/golden/STATUS.md` (a table per corpus, every failure with its reason, and every probe's question and verdict) and `status.json` (`git -C library diff mojo/golden/status.json` shows exactly what changed).
|
`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).
|
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).
|
||||||
|
|
||||||
@@ -104,19 +71,17 @@ The dialect markers in the pin are a cheap first look: `newer` patterns are synt
|
|||||||
|
|
||||||
| Path | What it is | Who writes it |
|
| Path | What it is | Who writes it |
|
||||||
|---|---|---|
|
|---|---|---|
|
||||||
| `library/mojo/pin.json` | The Mojo version, the godbolt compiler id, the arguments every program is built with (`build`), each source repository and the ref to use, and the dialect markers | You |
|
| `mojo/pin.json` | The Mojo version, the godbolt compiler id, each source repository and the ref to use, and the dialect markers | You |
|
||||||
| `library/mojo/mojo.lock.json` | What each ref resolved to: commit, zip sha256, and the directory inside the zip | `fetch`/`harvest` |
|
| `mojo/mojo.lock.json` | What each ref resolved to: commit, zip sha256, and the directory inside the zip | `fetch`/`harvest` |
|
||||||
| `library/mojo/corpus/` | Processed material, one directory per processor, each item with its provenance | `harvest` |
|
| `mojo/corpus/` | Processed material, one directory per processor, each item with its provenance | `harvest` |
|
||||||
| `library/mojo/corpus/SOURCES.md` | Which commit and license everything came from, what each processor found, every warning | `harvest` |
|
| `mojo/corpus/SOURCES.md` | Which commit and license everything came from, what each processor found, every warning | `harvest` |
|
||||||
| `library/mojo/licenses/` | Each source's license file, copied from the commit the pin's `licenseCheck` names | You |
|
| `mojo/probes/` | Our questions about the pinned compiler's behavior, one small program each | You (`new-probe`) |
|
||||||
| `library/THIRD_PARTY.md` | Every harvested file with its source and the license header it carries, and what each license check found | `emit` (and `harvest`, `verify`) |
|
| `mojo/local/` | Exercise programs, shipped in the app | You (`new-exercise`) |
|
||||||
| `library/mojo/probes/` | Our questions about the pinned compiler's behavior, one small program each | You (`new-probe`) |
|
| `mojo/stress/` | Realistic programs that test the interpreter, not shipped | You (`new-stress`) |
|
||||||
| `library/mojo/local/` | Exercise programs, shipped in the app | You (`new-exercise`) |
|
| `mojo/golden/<key>.json` | Godbolt's answer for one program, keyed by compiler, mode, arguments, stdin and source | `verify` |
|
||||||
| `library/mojo/stress/` | Realistic programs that test the interpreter, not shipped | You (`new-stress`) |
|
| `mojo/golden/STATUS.md` | Every item's verdict against the goldens | `status` (also `harvest`, `verify`) |
|
||||||
| `library/mojo/golden/<key>.json` | Godbolt's answer for one program, keyed by compiler, mode, arguments (the pin's, then the program's), stdin and source | `verify`; `prune` removes the ones nothing reads |
|
| `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` |
|
||||||
| `library/mojo/golden/STATUS.md` | Every item's verdict against the goldens | `status` (also `harvest`, `verify`) |
|
| `syntax/mojo.xml` | The same words as a KDE syntax for Pandoc listings (pplus-web copies it into its Quarto extension with its quarto-css task) | `harvest`/`emit` |
|
||||||
| `src/mojo/generated/` | What the app reads at run time: `pin.ts` (version, compiler, build arguments), `tokens.ts` (the words, removed words and the compiler's messages for them), `editor.ts` (comment and indentation rules), `programs.ts` (`library/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` |
|
|
||||||
| `library/syntax/mojo.xml` | The same words as a KDE syntax for Pandoc listings (pplus-web copies it into its Quarto extension with its quarto-css task) | `harvest`/`emit` |
|
|
||||||
|
|
||||||
Commit all of it. The stored answers are what make `pixi run test` and `mojo-status` work offline.
|
Commit all of it. The stored answers are what make `pixi run test` and `mojo-status` work offline.
|
||||||
|
|
||||||
@@ -150,20 +115,17 @@ A processor whose input files are missing at the pinned ref is skipped with a wa
|
|||||||
|
|
||||||
## Moving to a new Mojo version
|
## 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`, and check that pixi's channel has it (`pixi search -c https://conda.modular.com/max/ mojo`).
|
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 `library/mojo/pin.json`: `mojo.version`, `godbolt.compiler`, and `sources.modular.ref`; and `mojo = "==X.Y.Z"` in `pixi.toml` (pplus-web's too), then `pixi install`. A test holds the three names in the pin to one release, and `pixi.toml` and the documents to the pin. 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.
|
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; at a release tag it is empty, and a test says so.)
|
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 `library/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. A release can be tagged before its notes leave the nightly changelog (1.2.0 was: there is no `v1.2.0.md` at `mojo/v1.2.0`); the `release` processor then reads the changelog as the release's notes and says `notesFrom nightly-changelog`.
|
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, one request each and two at a time (`pixi run mojo-verify-dry` prints how many). Run it once, not in a loop; the public server is shared.
|
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 `library/mojo/golden/STATUS.md`. `git -C library 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. The compiler's wording changes too: the checker quotes it, and `tests/mojo-check.test.mjs` fails where a quoted message moved (1.2.0 names a `TString` by where its values live, not by their types).
|
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. Check each moved source's license at its new commit: read the repository's license files and the headers of what was harvested, copy the license file into `library/mojo/licenses/`, and update that source's `licenseCheck` in the pin (commit, date, file, sha256, what it says). `pixi run mojo-emit` rewrites `library/THIRD_PARTY.md`; `tests/third-party.test.mjs` fails until every source was checked at the commit the lock holds.
|
7. `pixi run test`, then commit the pin, the lock, the corpus, the goldens, and `src/mojo/generated/` together.
|
||||||
8. `pixi run mojo-local`, then `pixi run mojo-fuzz` with two or three seeds: the new compiler on every program core holds or generates. Then `pixi run library-verify-mojo` and `pixi run library-check` for the library's Mojo references.
|
|
||||||
9. `pixi run mojo-prune`: the old pin's answers are keyed by its compiler id, so nothing reads them any more (git keeps them).
|
|
||||||
10. `pixi run test`, then commit the pin, the lock, the corpus, the goldens and the library's records in pplus-library, and the new pointer, `pixi.toml`, `pixi.lock`, `src/mojo/generated/` and `src/library/generated.ts` here.
|
|
||||||
|
|
||||||
## Licenses and provenance
|
## Licenses and provenance
|
||||||
|
|
||||||
Every item records its repository, commit (or local zip hash), path, and license; `SOURCES.md` summarizes them, and `library/THIRD_PARTY.md` counts every harvested file by the license header it carries and lists the ones with none (the manual's snippets, cut from pages with no header, and Mojo Quest's starters). Modular's repository files carry Apache-2.0 WITH LLVM-exception headers, and the repository's own LICENSE covers the rest, the docs included. Mojo Quest's solutions carry the same headers, but the repository has no LICENSE file, and its starters come from a module with no header, 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.
|
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
|
## When something goes wrong
|
||||||
|
|
||||||
|
|||||||
+8
-10
@@ -2,13 +2,13 @@
|
|||||||
|
|
||||||
<!-- Written by tests/sync-coverage.test.mjs. Do not edit; rerun `npm test` to refresh. -->
|
<!-- 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 `library/pseudo/programs/` (55), and 17 one-construct fixtures (`tests/helpers/sync-programs.mjs`). 3 of the 89 have pseudo that does not read, by design (they teach the notation's error messages), and are left out below. That leaves **86 programs**.
|
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 |
|
| From pseudo to | Says it completely | Says it with a gap or a checker error | Cannot say it |
|
||||||
| --- | ---: | ---: | ---: |
|
| --- | ---: | ---: | ---: |
|
||||||
| Mojo | 83 | 3 | 0 |
|
| Mojo | 77 | 2 | 0 |
|
||||||
| lingo | 31 | 0 | 55 |
|
| lingo | 31 | 0 | 48 |
|
||||||
| matho | 3 | 0 | 83 |
|
| 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 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.
|
||||||
|
|
||||||
@@ -16,9 +16,7 @@ Mojo is a program-for-program translation that always produces something: a line
|
|||||||
|
|
||||||
These programs translate, with the listed lines left as a `raise Error`.
|
These programs translate, with the listed lines left as a `raise Error`.
|
||||||
|
|
||||||
| What it has no form for | Programs | Which |
|
Nothing.
|
||||||
| --- | ---: | --- |
|
|
||||||
| Programming+ could not translate this line into Mojo (the built-in EXACT, which Mojo's standard library has no function for). The generated code stops here with an error instead of guessing. | 1 | 50-float32.pseudo |
|
|
||||||
|
|
||||||
## Mojo: programs the translator refuses
|
## Mojo: programs the translator refuses
|
||||||
|
|
||||||
@@ -32,9 +30,9 @@ English is read by `readSteps`, whose grammar has no sentence for these.
|
|||||||
|
|
||||||
| What it has no form for | Programs | Which |
|
| What it has no form for | Programs | Which |
|
||||||
| --- | ---: | --- |
|
| --- | ---: | --- |
|
||||||
| steps outside a routine (every English step belongs to a routine) | 53 | 01-arithmetic.pseudo, 02-temperature.pseudo, 03-compound-interest.pseudo, 04-gcd-recursion.pseudo, and 49 more |
|
| 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 BYREF parameter | 4 | 06-fibonacci-memo.pseudo, 10-insertion-sort.pseudo, 26-swap-byref.pseudo, 55-statements.pseudo |
|
|
||||||
| a fixed-length ARRAY | 4 | ex:edit-distance, 05-primes-sieve.pseudo, 11-matrix-multiply.pseudo, 15-game-of-life.pseudo |
|
| 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 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 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 DEFINE set | 2 | ex:translate-codons, 21-sets.pseudo |
|
||||||
@@ -64,7 +62,7 @@ An equation lowers to one `FUNCTION` that returns a value; a program with output
|
|||||||
|
|
||||||
| What it has no form for | Programs | Which |
|
| What it has no form for | Programs | Which |
|
||||||
| --- | ---: | --- |
|
| --- | ---: | --- |
|
||||||
| steps outside a function (an equation is a function) | 49 | 01-arithmetic.pseudo, 02-temperature.pseudo, 03-compound-interest.pseudo, 04-gcd-recursion.pseudo, and 45 more |
|
| 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 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 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 function that answers BOOL (equations answer numbers) | 3 | ex:binary-search, fixture:early-return, fixture:forall |
|
||||||
|
|||||||
+10
-32
@@ -1,15 +1,14 @@
|
|||||||
# What each badge and verdict means
|
# What each badge and verdict means
|
||||||
|
|
||||||
Programming+ takes a procedure from an idea to Mojo to the machine. The idea is written in lingo (steps in plain English), matho (equations written in LaTeX), pseudo (pseudocode precise enough to run, prove and translate) or speco (a specification to prove against); then comes Mojo (Modular's programming language, pinned to version 1.2.0), then x86-64 on a model machine. pplus-web shows the badges; the verdicts behind them come from pplus-core (the prover, the fuzzer, the translators, the compiler's stored and live answers, the model machine). This page is kept here, beside what produces them.
|
pplus-web shows the badges; the verdicts behind them come from pplus-core (the prover, the fuzzer, the translators, the compiler's stored and live answers, the model machine). This page is kept here, beside what produces them.
|
||||||
|
|
||||||
Programming+ is built for checking work that someone or something else produced, so every claim it shows names what answered it, and none claims more than that. This page lists each one: who earns it, what it means, and what it does not mean. When a new badge or verdict is added, it gets a row here in the same commit. The texts below are pplus-web's (`src/ui/shell.ts`, `src/ui/provenance.ts`, `src/ui/home.ts`, `src/ui/library.ts`, `src/ui/views/`); pplus-web's `tests/trust.test.mjs` fails when a badge the site draws has no row here.
|
Programming+ is built for checking work that someone or something else produced, so every claim it shows names what answered it, and none claims more than that. This page lists each one: who earns it, what it means, and what it does not mean. When a new badge or verdict is added, it gets a row here in the same commit.
|
||||||
|
|
||||||
## Where code came from
|
## Where code came from
|
||||||
|
|
||||||
| Shown | Earned by | Means | Does not mean |
|
| Shown | Earned by | Means | Does not mean |
|
||||||
|---|---|---|---|
|
|---|---|---|---|
|
||||||
| **Generated from pseudo** | The Bridge's Mojo tab, always (`mojoProvenance` in pplus-web's `src/core/provenance.ts`); Mojo copied from it with **Edit in Developer** | The translator wrote this Mojo from the pseudo, literally, with a header comment saying so | That anyone has read it, or that it is the Mojo a person would write |
|
| **Generated from pseudo** | The Bridge's Mojo tab, always (`mojoProvenance` in pplus-web's `src/core/provenance.ts`); Mojo copied from it with **Edit in Developer** | The translator wrote this Mojo from the pseudo, literally, with a header comment saying so | That anyone has read it, or that it is the Mojo a person would write |
|
||||||
| **Generated from pseudo, with N best-practice rewrites** | The Best practices tab's rewrite of generated Mojo | The best-practice rules rewrote N places of the generated Mojo | That the rewrite was compiled. Copy it into the Developer area and Compile & run to ask |
|
|
||||||
| **Started from generated Mojo** | Generated Mojo edited in the Developer area (`mojoOrigin: 'generated-edited'`) | A person has changed generated Mojo | That the person reviewed the parts they did not change |
|
| **Started from generated Mojo** | Generated Mojo edited in the Developer area (`mojoOrigin: 'generated-edited'`) | A person has changed generated Mojo | That the person reviewed the parts they did not change |
|
||||||
| (badge cleared) | **I've reviewed this**, in the Developer area only | The person says they reviewed it; the header comment goes too | That anything checked the review. Compiling and editing never clear the badge |
|
| (badge cleared) | **I've reviewed this**, in the Developer area only | The person says they reviewed it; the header comment goes too | That anything checked the review. Compiling and editing never clear the badge |
|
||||||
|
|
||||||
@@ -17,18 +16,12 @@ Programming+ is built for checking work that someone or something else produced,
|
|||||||
|
|
||||||
| Shown | Earned by | Means | Does not mean |
|
| Shown | Earned by | Means | Does not mean |
|
||||||
|---|---|---|---|
|
|---|---|---|---|
|
||||||
| **Compiled on godbolt** (ran, exit N / compiled, did not run / did not compile / timed out) | An answer from the compile backend (`src/services/compile-backend.ts`, godbolt.org with Mojo 1.2.0 by default) for this exact source, input and build level, made in this browser | The real compiler answered as shown | That the program is right. The badge is keyed by a hash, so any edit, other input or other level removes it, and a share link never carries it |
|
| **Compiled on godbolt** (ran, exit N / did not compile / timed out) | An answer from the compile backend (`src/services/compile-backend.ts`, godbolt.org with Mojo 1.1.0 by default) for this exact source, input and build level, made in this browser | The real compiler answered as shown | That the program is right. The badge is keyed by a hash, so any edit, other input or other level removes it, and a share link never carries it |
|
||||||
| **Edited since compile** | An edit after a compile | The compiler's answer is for an earlier text | Anything about the current text |
|
| **Edited since compile** | An edit after a compile | The compiler's answer is for an earlier text | Anything about the current text |
|
||||||
| The Compile & run tab's own badge: **compiling**, **ran, exit 0**, **exited with N**, **compiled, did not run**, **did not compile**, **timed out**, **no answer** | The last request from this browser to the compile backend, and whether it is still waiting | What the backend answered for the source it was sent, built the one way Programming+ builds Mojo (`--target-cpu x86-64-v3 --fp-mode contract=off`, then `-O0` and line tables at the default level: [mojo-corpus.md](mojo-corpus.md#how-every-program-is-built)), so the listing is the same whichever of godbolt's machines answers; when the pane has changed since, the tab says so | That the current pane compiles, or anything when there was no answer (a network failure, for one). That `mojo build` on your own machine gives the same listing or the same last digits: with no arguments it targets your processor and fuses `a * b + c` into one rounding |
|
| **verified on Mojo 1.1.0** | An exercise's own program in `mojo/local/`, when godbolt's stored answer for that exact source passed the file's `# expect-stdout:` lines (`pixi run mojo-verify`) | The program printed what it should, on the real compiler | That the program is right on other inputs |
|
||||||
| **verified on Mojo 1.2.0** | An exercise's own program in `library/mojo/local/`, shown unchanged, when godbolt's stored answer for that exact source passed the file's own expectation: its `# expect-stdout:` lines, or `# expect: fail` for a starter whose bug the student is to find (`pixi run mojo-verify`) | The program did what its file says it should, on the real compiler | That the program is right on other inputs, or that a starter is right at all |
|
| A Mojo checker error, warning or note | Programming+'s own checker (`src/mojo/`) | The compiler would report this. The checker may never report an error on a program the compiler accepts (`tests/mojo-check.test.mjs`) | That a program without checker errors compiles. Only the compiler says that |
|
||||||
| **not verified** | An exercise's own program, shown unchanged, with no passing stored answer for that exact source | Not yet asked, or the answer did not pass; the badge's tooltip says which | That it fails |
|
|
||||||
| **your edits** | An exercise's own program after the student changed it | The text is no longer the one that was verified | Anything about the new text; Compile & run asks about it |
|
|
||||||
| **Mojo 1.2.0** (no other word) | A Mojo pane whose text is neither an exercise's own program nor generated | The pinned version the checker, the interpreter and Compile & run use | Anything about this program |
|
|
||||||
| The home page's **verified** chip on a problem | The problem's own Mojo program has the **verified on Mojo 1.2.0** badge | As that badge | As that badge |
|
|
||||||
| The home page's **your edits saved** chip | A saved version of the problem in this browser | Opening it brings back the saved text | Anything about that text |
|
|
||||||
| A Mojo checker error, warning or note | Programming+'s own checker (`src/mojo/`) | The compiler would report this. The checker may never report an error on a program the compiler accepts: `tests/mojo-check.test.mjs` holds it to that on every program the corpus holds with a stored answer, and `pixi run mojo-local` and `mojo-fuzz` on the programs they build | That a program without checker errors compiles. Only the compiler says that |
|
|
||||||
| A **best practices** note | The optional helper (`src/mojo/practices.ts`), off by default | A more idiomatic way to write a line, whose rewrite keeps the output the same where it offers one | An error. Notes never look like the compiler |
|
| A **best practices** note | The optional helper (`src/mojo/practices.ts`), off by default | A more idiomatic way to write a line, whose rewrite keeps the output the same where it offers one | An error. Notes never look like the compiler |
|
||||||
| Mojo output in the Run view and stepper | Programming+'s Mojo interpreter (`src/mojo/interp.ts`) | For a program the compiler builds, what it prints, or the interpreter declines and says why. One listed exception: `probes/struct-field-loop-copy`, which Mojo 1.2.0 builds into a program that crashes (it frees a struct's List field twice); the interpreter runs it as written, and the test holds that difference by name. `tests/mojo-run.test.mjs` holds it to that on every program godbolt ran, from the stored answers; `pixi run mojo-local` and `mojo-fuzz` hold it to the pinned compiler on a developer's machine | That the program compiles. The interpreter can run a program the compiler rejects (`print(Int(3.9))` prints `3` here; Mojo 1.2.0 refuses to build it), so Compile & run is the word on whether it compiles. On a program outside the corpus, agreement is the rule the tests hold it to, not a proof. Its FLOAT arithmetic is the compiler's as Programming+ builds it: every build passes `--fp-mode contract=off` (`library/mojo/pin.json`), so `a * b + c` is rounded twice, as the interpreter rounds it (`probes/float-contract-runtime-off`). Three things it does not promise. The last digits of a program built another way: with Mojo's default, `--fp-mode contract=fast`, the built program fuses a multiply with an add or subtract into one rounding where the operands arrive at run time (`probes/float-contract-runtime` is built that way on purpose, and `pixi run mojo-local` lists it as the interpreter's one difference of this kind), so `mojo build` on your own machine can differ in a last digit. A float raised to a power that is not a whole number, and std.math's transcendental functions (`sin`, `cos`, `exp`, `log`, `cbrt` and the others), which Mojo computes with routines of its own or the C library's, so the interpreter declines them (a whole power it computes as Mojo does, by squaring; `fma`, `hypot`, `nextafter`, `ulp`, `copysign`, `sqrt`, `gcd`, `lcm` and `comb` it computes exactly as Mojo does, each held to a probe), as it declines random numbers, whose values come from Mojo's own generator. And input: the interpreter hands `input()` one line per call, as a terminal does; in Mojo 1.1.0 and 1.2.0 each `input()` opens its own buffered reader, so when the input is a pipe (Compile & run, a script) the first call takes every line and the second raises `EOF` |
|
| Mojo output in the Run view and stepper | Programming+'s Mojo interpreter (`src/mojo/interp.ts`) | Exactly what godbolt printed for the same program, or the interpreter declines and says why (`tests/mojo-run.test.mjs`) | A prediction. The interpreter does not guess |
|
||||||
|
|
||||||
## What a proof says
|
## What a proof says
|
||||||
|
|
||||||
@@ -36,18 +29,17 @@ The Prove tab reports every obligation in three statuses (`src/engines/pseudo/vc
|
|||||||
|
|
||||||
| Shown | Earned by | Means | Does not mean |
|
| Shown | Earned by | Means | Does not mean |
|
||||||
|---|---|---|---|
|
|---|---|---|---|
|
||||||
| **Proved** | The built-in prover (`solver.ts`), on every path it examined, in a unit it examined completely | The claim follows from what is known, in the notation's number model: INTEGER as whole numbers of any size, the sized types (INT8 … UINT64) exactly, with an `overflow` obligation wherever a value could leave its range, FLOAT and FLOAT32 as finite numbers whose rounding is not seen into. The prover is meant to be sound: `tests/prover-soundness.test.mjs` holds it to every known hole (the regression programs in `library/pseudo/prover/`), to a canary, and to every corpus program run and fuzzed; an audit in November 2026 closed 18 rules that proved what a run breaks. In a program that says `USE IEEE` nothing is marked proved | That the Mojo made from the program has the same property. A 64-bit `Int` wraps and a `Float64` becomes `inf` or `nan`; the `int-model` and `float-model` notes say when a proof leans on the number model. That the prover has no hole left: a "proved" that a run breaks is a soundness bug ([engines.md](engines.md#soundness)) |
|
| **Proved** | The built-in prover (`solver.ts`), on every path it examined, in a unit it examined completely | The claim follows from what is known, in the notation's number model: INTEGER as whole numbers of any size, FLOAT as finite numbers whose rounding is not seen into. The prover is sound (`tests/prover-soundness.test.mjs`) | That the Mojo made from the program has the same property. A 64-bit `Int` wraps and a `Float64` becomes `inf` or `nan`; the `int-model` and `float-model` notes say when a proof leans on the number model. A unit marked **partial** shows no claim as proved |
|
||||||
| **Broken** | A generated input (the fuzzer, seeded) or a run that breaks the claim at that place | There is an input for which the claim is false, and **Step through** shows it | Anything about other claims. A run outranks the prover: a proved obligation that an input breaks is shown as broken (and would be a soundness bug) |
|
| **Broken** | A generated input (the fuzzer, seeded) or a run that breaks the claim at that place | There is an input for which the claim is false, and **Step through** shows it | Anything about other claims. A run outranks the prover: a proved obligation that an input breaks is shown as broken (and would be a soundness bug) |
|
||||||
| **Open** | Neither of the above | The checker could not finish the argument, usually because a loop needs an INVARIANT | That the claim is false |
|
| **Open** | Neither of the above | The checker could not finish the argument, usually because a loop needs an INVARIANT | That the claim is false |
|
||||||
| **partial: not every path was examined**, on a unit | The prover left some paths of the unit unexamined (more paths than its limit, or past its time limit) | Nothing in the unit is marked proved: what it would have proved shows as open | That anything in it is wrong |
|
|
||||||
| An invariant "the checker found on its own" | Inference in `vcgen.ts`, kept only at a fixed point | It holds on entry and survives every pass, and the proof used it | That it is the invariant a reader needs |
|
| An invariant "the checker found on its own" | Inference in `vcgen.ts`, kept only at a fixed point | It holds on entry and survives every pass, and the proof used it | That it is the invariant a reader needs |
|
||||||
|
|
||||||
## What testing says
|
## What testing says
|
||||||
|
|
||||||
| Shown | Earned by | Means | Does not mean |
|
| Shown | Earned by | Means | Does not mean |
|
||||||
|---|---|---|---|
|
|---|---|---|---|
|
||||||
| A routine's cases in the Tests tab, under **no failures**, **N ways of failing** or **not tested** | The fuzzer (`src/common/fuzz.ts`), with the seed and input count shown; **not tested** when it cannot generate inputs for the routine, with the reason | Every input listed was run and checked against each claim and limit | That untried inputs pass. "Held on 300 inputs" is evidence, not proof |
|
| A routine's cases in the Tests tab | The fuzzer (`src/common/fuzz.ts`), with the seed and input count shown | Every input listed was run and checked against each claim and limit | That untried inputs pass. "Held on 300 inputs" is evidence, not proof |
|
||||||
| A failure's shrunk input | Shrinking in the fuzzer | The smallest input it found that fails the same way | The smallest input that fails, or the only one |
|
| A failure's smallest input | Shrinking in the fuzzer | The smallest input it found that fails the same way | The only failing input |
|
||||||
|
|
||||||
## What a translation says
|
## What a translation says
|
||||||
|
|
||||||
@@ -55,7 +47,7 @@ The Prove tab reports every obligation in three statuses (`src/engines/pseudo/vc
|
|||||||
|---|---|---|---|
|
|---|---|---|---|
|
||||||
| ⇄ in step (lingo, matho, speco) | The translator, which reads its own output back and holds it to the pseudo (`tests/sync-lingo.test.mjs`, `sync-matho.test.mjs`, `sync-speco.test.mjs`) | The two panes describe the same program, as far as the round trip checks | A proof that they are equivalent on every input |
|
| ⇄ in step (lingo, matho, speco) | The translator, which reads its own output back and holds it to the pseudo (`tests/sync-lingo.test.mjs`, `sync-matho.test.mjs`, `sync-speco.test.mjs`) | The two panes describe the same program, as far as the round trip checks | A proof that they are equivalent on every input |
|
||||||
| ⚠ not in step | A language that cannot say the program, or a pane that does not read | The pane keeps its last text and says why | That the pane is wrong |
|
| ⚠ not in step | A language that cannot say the program, or a pane that does not read | The pane keeps its last text and says why | That the pane is wrong |
|
||||||
| Generated Mojo agreeing with the pseudo | `tests/sync-mojo.test.mjs`, over every exercise and corpus program, in core's interpreter; and `pixi run mojo-local` and `mojo-fuzz`, on the pinned compiler itself, over those programs, the library's routines, and generated ones | On those programs, the Mojo compiles and prints what the pseudo prints: in the tests by core's interpreter, and by the compiler only on a machine with the pinned Mojo (`mojo-local` and `mojo-fuzz`) | That the translator is verified. Where a line has no faithful Mojo, the translation stops with `not translated` rather than guess. Numbers agree to their last digits or nearly: the compiler's `std.math` is its own (in Mojo 1.2.0, `**` to a fractional power is good to about 13 digits and to a whole power, done by repeated multiplication, to the last digit or two; `exp` and `cosh` are good to about 13 digits near 1 and about 10 at 100 (`probes/float-cosh-accuracy`); `log2` to about 9; a whole exponent near 1e10 stops the built program, and `gcd` of an even number and a much larger odd one does not come back), while its arithmetic is the pseudo's, each FLOAT operation rounded on its own, since every program is built with contraction off; the translation carries a note where it writes `**` or `log2`. Mojo writes some FLOATs as other text (6.02e+23 for 6.02e23), so a FLOAT made into text is translated where it is printed and is `not translated` where the program uses the text itself |
|
| Generated Mojo agreeing with the pseudo | `tests/sync-mojo.test.mjs`, over every exercise and corpus program | On those programs, the Mojo prints what the pseudo prints | That the translator is verified. Where a line has no faithful Mojo, the translation stops with `not translated` rather than guess |
|
||||||
|
|
||||||
## What the machine says
|
## What the machine says
|
||||||
|
|
||||||
@@ -63,17 +55,3 @@ The Prove tab reports every obligation in three statuses (`src/engines/pseudo/vc
|
|||||||
|---|---|---|---|
|
|---|---|---|---|
|
||||||
| Registers, caches, pipeline and counters in the Hardware area | The model machine (`src/engines/asm86/`), on the preset machine named in Setup | What that model does with these instructions | A measurement of a real processor. Cycle counts are a teaching model; compare a run with itself across edits |
|
| Registers, caches, pipeline and counters in the Hardware area | The model machine (`src/engines/asm86/`), on the preset machine named in Setup | What that model does with these instructions | A measurement of a real processor. Cycle counts are a teaching model; compare a run with itself across edits |
|
||||||
| "stopped: … standard library, not on the model machine" | A call into a function the model does not have | The real program would enter the library here | That the library call does anything in particular |
|
| "stopped: … standard library, not on the model machine" | A call into a function the model does not have | The real program would enter the library here | That the library call does anything in particular |
|
||||||
|
|
||||||
## Library routines
|
|
||||||
|
|
||||||
A routine of pplus-library (`USE md`) carries the record of `pixi run library-check` ([library.md](library.md)).
|
|
||||||
|
|
||||||
| Shown | Earned by | Means | Does not mean |
|
|
||||||
|---|---|---|---|
|
|
||||||
| **Cases pass** | Running the pseudo on the cases in `routine.json` | The routine gives those results; they are what every reference is held to | That the results are right for other inputs |
|
|
||||||
| **Prover: pass** | Every obligation of the routine proved, as for any pseudo | Its contracts hold for every input that meets its REQUIRE, in the notation's number model | Anything about the value of FLOAT arithmetic beyond what the contracts say |
|
|
||||||
| **Prover: open** | Some obligation not proved, none broken | The routine's comment says which and why (usually FLOAT rounding, which is opaque to the prover; `tests/documents.test.mjs` fails when the comment does not mention it) | That it is wrong |
|
|
||||||
| **A reference agrees** | Python, C at -O0 and -O2, core's Mojo interpreter, the pinned Mojo compiler on the machine that ran the check (`compiler`), or the pinned compiler on godbolt, run on the cases. A C or Mojo reference's program holds no case: it reads every case's arguments from stdin at run time, each FLOAT bit for bit (`tests/library-harness.test.mjs`), so the compiler cannot work them out while it builds | That implementation, at that level, prints the pseudo's results exactly, or within the stated tolerance, computed by the code the compiler made for inputs it did not know. A Mojo reference is built with the pin's arguments, contraction off among them, so that code rounds each FLOAT operation on its own, as the pseudo does; Mojo's own math library (`exp`, `log2`, `cosh`, `**`) is not the pseudo's, and a reference that calls it states a tolerance and why | That it agrees on other inputs, or built with other flags: with Mojo's defaults the code fuses a multiply and an add into one rounding where it can (`probes/float-contract-runtime`), and a last digit can differ |
|
|
||||||
| **Mojo: unverified** | No stored answer from the pinned compiler for that exact program and input | Not yet asked (`pixi run library-verify-mojo`) | That it fails |
|
|
||||||
| **Proof: pass** | The pinned Dafny verified the proof file (or its stored verdict for this exact text) | The method is correct over exact numbers, as the proof states it | That the FLOAT version computes the same digits: rounding is outside the proof |
|
|
||||||
|
|
||||||
-1
Submodule library deleted from e5ae0904cf.
@@ -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")
|
||||||
+143
@@ -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()
|
||||||
+71
@@ -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
|
||||||
+53
@@ -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()
|
||||||
+47
@@ -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()
|
||||||
+40
@@ -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?
|
||||||
+38
@@ -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]()
|
||||||
+45
@@ -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]()
|
||||||
+36
@@ -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]())
|
||||||
+56
@@ -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)
|
||||||
+60
@@ -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)
|
||||||
+71
@@ -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)
|
||||||
+115
@@ -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)
|
||||||
+96
@@ -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
|
||||||
+118
@@ -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
|
||||||
+280
@@ -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
|
||||||
+21
@@ -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"):
|
||||||
|
...
|
||||||
+22
@@ -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
|
||||||
+276
@@ -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()
|
||||||
+22
@@ -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():
|
||||||
|
...
|
||||||
+72
@@ -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
|
||||||
+305
@@ -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
|
||||||
+17
@@ -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()]
|
||||||
+135
@@ -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
|
||||||
|
)
|
||||||
Loaded 100 of 1512 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user