858 Commits
Author SHA1 Message Date
Patrick Quist b0c6715a89 Fix blank right-hand pane in tree shortlink layouts (#9028) 2026-08-18 18:29:04 +02:00
Patrick Quist 58d1561e2e Pass CUDAToolkit_ROOT for cuda clang compilers (#9023) 2026-08-15 15:03:13 +02:00
Patrick QuistandClaude Opus 5 500c09675b MCP: proxy compiles for remotely-hosted compilers (#9016)
cc @mattgodbolt — this is in the MCP endpoint from #8644.

## The problem

`compile` in the MCP tool calls `baseCompiler.compile()` directly, so a
compiler served by a sub-server gets attempted on whichever node handled
the MCP request. There's no compiler binary there to launch, so every
remotely-hosted compiler fails through `/mcp`:

```
runChild():486 Launching child process failed
```

Reproducible on production right now — `vcpp_v19_51_VS18_6_x64` through
`compiler-explorer.com/mcp` fails, while the same id and options through
`/api/compiler/<id>/compile` works. It affects any remote, not just the
Windows ones.

`CompileHandler.handle` has the branch that makes this work for REST:

```ts
const remote = compiler.getRemote();
if (remote) {
    req.url = remote.path;
    this.proxy.web(req, res, {target: remote.target, changeOrigin: true}, ...);
    return;
}
```

There's no equivalent anywhere in `lib/mcp` — `git log -S"getRemote" --
lib/mcp` is empty, so this has been the case since the endpoint landed.

## The change

Check `getRemote()` and, when it's set, POST an equivalent request to
`remote.target + remote.path` rather than compiling locally. A tool call
has no `req`/`res` to hand to `http-proxy`, hence an outbound `fetch`
instead of the proxy. The sub-server returns the same JSON shape
`compile()` returns locally, so truncation, `buildResult` and
`execResult` handling below are untouched.

One wart: `result` is annotated `Awaited<ReturnType<typeof
baseCompiler.compile>>` rather than `CompilationResult`, because the
declared wire type has `asm?: string | ParsedAsmResultLine[]` and
`truncateLines` wants the array form — typing it as `CompilationResult`
doesn't compile. There's a cast on the remote branch with a comment
explaining why. Happy to do this differently if you'd rather.

## Testing

Unit tests: the existing fake compiler had no `getRemote`, so it's added
there; two new cases cover the remote path posting to the sub-server
(and never calling `compile()` locally) and a failing sub-server
response surfacing as a tool error.

Manually, against a local instance configured with the `gpu` and
`winprod` remotes:

| compiler | before | after |
| --- | --- | --- |
| `vcpp_v19_51_VS18_6_x64` `/O2` | `runChild():486` | `code 0`, `lea
eax, DWORD PTR [rcx+1]` |
| `vcpp_v19_51_VS18_6_x86` `/O2 /std:c++20` | — | `code 0`, `mov eax,
DWORD PTR _x$[esp-4]` |
| `clang-cl2216-v19_50_VS18_2` `/O2` | — | `code 0` |

Compile errors propagate too: a deliberate typo returns `code 2` with
`<source>(1): error C2065: 'nope': undeclared identifier`.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-14 17:38:37 -05:00
Hurairabaloch 62d87f264d Enable clang-tidy for Clang-CUDA builds (#8996)
## Summary
- enable clang-tidy for Clang-CUDA compiler groups in the default and
production CUDA configurations
- resolve clang-tidy from the selected Clang-CUDA toolchain while
preserving version suffixes
- add focused tests for CUDA and non-CUDA executable selection

Closes #6944

## Test plan
- [x] `npm run test:props` (90 tests)
- [x] `npm run ts-check`
- [x] `cross-env SKIP_EXPENSIVE_TESTS=true npx vitest related --run` (39
tests)

## AI assistance
AI assistance was used for codebase navigation and drafting. The final
diff was reviewed and the listed checks were run locally.
2026-08-13 20:54:42 -05:00
1863cec885 Accept GoldenLayout format in /clientstate/ URLs (#8862)
The /z/ stored-link handler already supports both ClientState
(sessions-based) and GoldenLayout (content-based) JSON formats, but the
/clientstate/ endpoint only accepted ClientState and always converted it
to GoldenLayout using the default layout.

Extract a shared configToGoldenLayout() method that checks for a
'content' key (GoldenLayout format) and passes it through directly, or
converts from ClientState otherwise. Both storedStateHandler and
unstoredStateHandler now use this method, making the two endpoints
consistent in what formats they accept.

This allows /clientstate/ URLs to carry full GoldenLayout state
including custom panel layouts (e.g., editor-on-top with conformance
view below), which was previously only possible via stored /z/ links.

<!-- THIS COMMENT IS INVISIBLE IN THE FINAL PR, BUT FEEL FREE TO REMOVE
IT
Thanks for taking the time to improve CE. We really appreciate it.
Before opening the PR, please make sure that the tests & linter pass
their checks,
  by running `make check`.
In the best case scenario, you are also adding tests to back up your
changes,
  but don't sweat it if you don't. We can discuss them at a later date.
Feel free to append your name to the CONTRIBUTORS.md file
Thanks again, we really appreciate this!
-->

Co-authored-by: jberne4 <jberne4@bloomberg.net>
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-08-11 11:19:28 -05:00
Patrick Quist 764483e54f Pluggable build systems: Cargo, Maven and Make alongside CMake (#8994) 2026-08-09 22:06:51 +02:00
umayyah 87f90be050 Fix crash in CFG generation when a conditional jump is the last instruction (#8974)
Fixes #6902

## What was happening
Reproducing the Clean example from the issue, the CFG pane didn't just
draw
a wrong graph — it actually crashed the whole compile with:

TypeError: Cannot set properties of undefined (setting 'nameId')
    at BaseCFGParser.extractAltJmpTargetName

## Root cause
`extractAltJmpTargetName` assumes a conditional jump is never the last
instruction of a function — it always tries to write a generated name
onto
"the next basic block" (`arrBB[bbIdx + 1]`). When a function's last
basic
block ends in a conditional jump with no fallthrough block after it,
`arrBB[bbIdx + 1]` doesn't exist, and the code crashes trying to set a
property on `undefined`.

I couldn't get a working Clean compiler locally, so I wasn't able to
confirm Clean's exact label format, but I could reliably reproduce the
exact same crash/stack trace with 3 lines of synthetic assembly (see the
added test case) — any input that leaves a conditional jump as the final
instruction of a function hits this.

## Fix
Guard the write so it only happens when a next block actually exists.
The
frontend layout code (`graph-layout-core.ts`) already tolerates edges
that
point at a node ID that doesn't exist (there's an existing comment there
about exactly this: "Backend can return dest: null"), so this degrades
gracefully instead of crashing.

## Note
This fixes the crash. The original report also mentioned Clean's
*labels*
getting misidentified as separate functions in the graph itself — that's
a related but separate issue (in `isFunctionEnd()`'s assumption that
local
labels are dot-prefixed, GNU-`as`-style). I didn't have a way to verify
Clean's actual label format to fix that part with confidence, so I've
left
it for a possible follow-up.

## Testing
Added `test/cfg-cases/cfg-base.cond-jmp-last-instruction.json` and a new
`describe('base', ...)` block in `test/cfg-tests.ts`. Confirmed it fails
with the original crash on unpatched code and passes with the fix.
2026-08-06 07:30:26 -05:00
narpfel 788815da07 Fix stack usage view for GCC nightly (#8973)
GCC nightly has changed its `-fstack-usage` output to include the
mangled function name, so currently the stack usage view shows the
demangled function name instead of the stack frame size, e. g.
`square(int) bytes, static`; see https://godbolt.org/z/xxhWfzqha.
2026-08-06 06:59:52 -05:00
1c24af8e76 Cleanup gcc pass dumps from file/line info (#8931)
Following the review in
https://github.com/compiler-explorer/compiler-explorer/pull/8826/changes/c4d8590f6a992b4478f9f08b41af2ac05bff3402#r3476267780,
this PR tries to clean up file/line info from gcc dumps.

Example `expand (rtl)` output, for the default C++ source example:
```

;; Function square (_Z6squarei, funcdef_no=0, decl_uid=2861, cgraph_uid=1, symbol_order=0)


;; Generating RTL for gimple basic block 2

;; Generating RTL for gimple basic block 3


try_optimize_cfg iteration 1

Merging block 3 into block 2...
Merged blocks 2 and 3.
Merged 2 and 3 without moving.
Merging block 4 into block 2...
Merged blocks 2 and 4.
Merged 2 and 4 without moving.
Removing jump 11.
Merging block 5 into block 2...
Merged blocks 2 and 5.
Merged 2 and 5 without moving.


try_optimize_cfg iteration 2



;;
;; Full RTL generated for this function:
;;
(note 1 0 4 NOTE_INSN_DELETED)
(note 4 1 2 2 [bb 2] NOTE_INSN_BASIC_BLOCK)
(insn 2 4 3 2 (set (mem/c:SI (plus:DI (reg/f:DI 93 virtual-stack-vars)
                (const_int -4 [0xfffffffffffffffc])) [1 num+0 S4 A32])
        (reg:SI 5 di [ num ])) :2:21 -1
     (nil))
(note 3 2 6 2 NOTE_INSN_FUNCTION_BEG)
(insn 6 3 7 2 (set (reg:SI 100)
        (mem/c:SI (plus:DI (reg/f:DI 93 virtual-stack-vars)
                (const_int -4 [0xfffffffffffffffc])) [1 num+0 S4 A32])) :3:18 -1
     (nil))
(insn 7 6 10 2 (parallel [
            (set (reg:SI 98 [ _2 ])
                (mult:SI (reg:SI 100)
                    (reg:SI 100)))
            (clobber (reg:CC 17 flags))
        ]) :3:18 -1
     (nil))
(insn 10 7 14 2 (set (reg:SI 99 [ <retval> ])
        (reg:SI 98 [ _2 ])) :3:18 discrim 1 -1
     (nil))
(insn 14 10 15 2 (set (reg/i:SI 0 ax)
        (reg:SI 99 [ <retval> ])) :4:1 -1
     (nil))
(insn 15 14 0 2 (use (reg/i:SI 0 ax)) :4:1 -1
     (nil))
```

---------

Co-authored-by: Ofek Shilon <oshilon@speedata.io>
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
2026-07-29 15:46:52 +02:00
Ardit Tirana 8519254bb8 fix: consolidate /z/<id> URL parsing into a single robust helper (#8847) 2026-07-27 18:54:17 +02:00
07226d33bf Reapply extraBodyClass-driven branding, validating via the manifest in production (#8935)
Reapplies #8755, which was reverted in 463e3e70f after it broke the
staging deploy:

```
error: Top-level error (shutting down): Missing branding assets for extraBodyClass='staging'
in /infra/.deploy/static: favicon-staging.ico, site-logo-staging.svg
```

### What went wrong

`validateBrandingAssets` checked `staticPath` on the local filesystem.
That's correct for dev and local prod runs, but AWS deploys ship **two**
packages (`build-dist.sh`): the node app tarball (no `static/` at all)
and the static bundle, which goes to the CDN
(`staticUrl=https://static.ce-cdn.net/`). Production nodes never have
the branding files on disk, so any env with `extraBodyClass` set
(staging, beta, win\*) died at startup. Prod itself has an empty
`extraBodyClass`, which is why the check short-circuited there and the
bug only surfaced on the staging deploy.

### The fix (second commit)

The webpack manifest **does** ship with the node app, and lists every
asset copied from `public/` into the static bundle. So in production,
validate the derived `favicon-<class>.ico` / `site-logo-<class>.svg`
names against **manifest keys** instead of the filesystem; dev keeps the
on-disk check against `public/`. This preserves the fail-fast-on-typo
behaviour #8755 wanted, checking the thing that actually describes what
shipped to the CDN. If the manifest can't be loaded we're already on the
existing warn-and-fall-back handler, so validation is skipped rather
than fatal.

`setupStaticMiddleware` now takes the parsed manifest (loaded once in
`setupWebServer` via new `loadStaticManifest`) instead of reading it
itself.

### Verification

- Fresh **production** webpack build: all six env asset pairs (dev,
beta, staging, winprod, winstaging, wintest) appear as plain-name keys
in `manifest.json` (the win\* symlink placeholders are dereferenced on
copy).
- Booted the built `out/dist` server code in the exact deploy layout
(`staticUrl` set, nonexistent `staticPath`, `extraBodyClass=staging`):
boots cleanly and renders `favicon-staging.ico` +
`site-logo-staging.svg`; a mistyped class still fails startup with a
clear error.
- New regression tests pin both behaviours at the `setupWebServer` level
with a shipped-manifest-only layout.

⚠️ Merge timing: prod's empty `extraBodyClass` never exercises this path
— the real test is the next **staging** deploy, so this should merge
when someone (me) is ready to deploy staging and watch it.

cc @partouf — sorry again for the breakage; this validates against the
manifest rather than expecting the CDN bundle's files on local disk.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: mattgodbolt-molty <mattgodbolt-molty@users.noreply.github.com>
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-07-20 21:37:49 +01:00
Partouf 463e3e70f0 Revert "Drive env branding from extraBodyClass alone (#8755)"
This reverts commit 13358939ce.
2026-07-19 23:55:46 +02:00
13358939ce Drive env branding from extraBodyClass alone (#8755)
The favicon selector and logo overlay used to be hard-coded switches
over the env name array (favicon) and a chained if/else in logo.pug.
Adding a new environment meant editing both, the favicon allowlist, and
the tests.

Convert both to a convention driven by extraBodyClass:
favicon-<class>.ico and site-logo-<class>.svg. logo.pug becomes one
unconditional overlay tag. getFaviconFilename takes the class string
directly.

Add validateBrandingAssets, called once during setupWebServer, which
throws if the configured assets are missing. Typos in extraBodyClass now
fail at startup with a clear error rather than serving a broken favicon.

isFaviconRequest becomes a regex matching favicon-*.ico so the log
filter no longer needs a per-env list (and previously didn't match
because req.path has a leading slash).

A new environment is now: drop two files in public/, set extraBodyClass
in the env properties file. No TS or pug changes.

---------

Co-authored-by: Matt Godbolt <mattgodbolt@hudson-trading.com>
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
2026-07-14 17:18:25 +01:00
c425932877 Mask temp paths by the CE marker, not the live os.tmpdir() (#8920)
maskRootdir() built its strip-regex from this process's os.tmpdir(), so
it only masked paths whose root matched the current tmpdir. That is
fragile in two real cases:

- The path being masked is recorded when the compile runs and need not
share the masking process's tmpdir. Snapshots/fixtures that freeze
/tmp/... paths only mask on hosts where os.tmpdir() is /tmp (they fail
where it is e.g. /usr/tmp).
- On macOS os.tmpdir() returns /var/folders/... while real temp paths
often resolve via /private/var/folders/..., so masking silently missed.
- A configured temp root (temp dirs created outside os.tmpdir()) was
never matched at all.

Key the regex off the distinctive ce_temp_prefix marker instead,
matching whatever path segments precede it. This is tmpdir-independent
and unifies the Windows and non-Windows branches into one rule (also
masking embedded temp paths like `-I/tmp/.../include` on Windows, which
the old anchored branch missed).

Adds unit tests for maskRootdir (previously untested) covering /tmp,
/usr/tmp, macOS /private/var, Windows, the -I include case, and non-temp
paths left untouched.

<!-- THIS COMMENT IS INVISIBLE IN THE FINAL PR, BUT FEEL FREE TO REMOVE
IT
Thanks for taking the time to improve CE. We really appreciate it.
Before opening the PR, please make sure that the tests & linter pass
their checks,
  by running `make check`.
In the best case scenario, you are also adding tests to back up your
changes,
  but don't sweat it if you don't. We can discuss them at a later date.
Feel free to append your name to the CONTRIBUTORS.md file
Thanks again, we really appreciate this!
-->

---------

Co-authored-by: Matt Godbolt <mattgodbolt@hudson-trading.com>
Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
2026-07-14 15:30:54 +01:00
Sirui MuandMatt Godbolt 7a6af91bc9 Enable AST output for Python (#8858)
This patch adds support for viewing the abstract syntax tree (AST) of
Python source code in Compiler Explorer, matching the existing AST
viewer feature for C/C++ (Clang AST).

- This patch adds a helper script `ast_dump.py` that parses and dumps
the AST for a Python source code file. `python -m ast` should also work,
but it's not available in old versions of Python.
- This patch adds an AST parser for Python which mimics the structure of
the C/C++ AST parser. It also updates the Python compiler to enable AST
output.
- All existing and new tests pass.

Assisted-by: GitHub Copilot / DeepSeek v4 Flash
Assisted-by: GitHub Copilot / DeepSeek v4 Pro

<!-- THIS COMMENT IS INVISIBLE IN THE FINAL PR, BUT FEEL FREE TO REMOVE
IT
Thanks for taking the time to improve CE. We really appreciate it.
Before opening the PR, please make sure that the tests & linter pass
their checks,
  by running `make check`.
In the best case scenario, you are also adding tests to back up your
changes,
  but don't sweat it if you don't. We can discuss them at a later date.
Feel free to append your name to the CONTRIBUTORS.md file
Thanks again, we really appreciate this!
-->

Co-authored-by: Matt Godbolt <matt@godbolt.org>
2026-07-14 08:46:10 +01:00
Cycle1337 ed127f3933 Fix compiler tool ID slimming for cached arrays (#8893) 2026-07-08 09:42:37 +02:00
3d5a62fe6b Re-add CI check enforcing license header banners (#8883)
## What & why

We used to enforce the BSD-2-Clause license banner on every source file
via `eslint-plugin-header`. That check was lost when we migrated from
ESLint to Biome (#7033), which has no equivalent rule. This PR
reinstates it as a standalone node script, modelled on the existing
`etc/scripts/check-frontend-imports.js`.

### Why a script rather than a Biome rule
Biome 2.x has no built-in license/header rule and no plugin equivalent
to `eslint-plugin-header`; its experimental GritQL plugins aren't suited
to whole-file-prefix matching. A script needs zero new dependencies and
gives full control over scope and exemptions.

## The check (`etc/scripts/check-license-headers.js`)

A file "has an appropriate banner" if, ignoring an optional shebang, it
opens with a `// Copyright (c) …` line **and** contains the BSD-2-Clause
disclaimer body. The year and copyright holder are intentionally **not**
constrained — the tree legitimately has many holders (Compiler Explorer
Authors, Arm, Microsoft, HRT, individuals). The `(c)`/`(C)` marker is
matched case-insensitively.

**Scope:** `.ts/.js/.mjs/.cjs` under `lib/ static/ shared/ types/ test/
cypress/`.

**Exempt:** generated files (`lib/asm-docs/generated`), vendored
(`docenizer/vendor`), `.d.ts`, and three third-party ports that carry
their own upstream license — `static/ansi-to-html.ts` (MIT),
`lib/node-graceful.ts` (MIT), `shared/rison.ts` (Nanonid/rison port).

**Wired into:** CI (`test-and-deploy.yml`), `npm run check`, the `make
pre-commit` target, the husky pre-commit hook, and `lint-staged` (per
staged file).

Usage:
```
node ./etc/scripts/check-license-headers.js            # scan the tracked tree
node ./etc/scripts/check-license-headers.js <files...> # scan specific files (lint-staged)
```

## Backfill

The check surfaced **42 CE-authored files** missing the banner. This PR
backfills them all with the standard `Copyright (c) <year>, Compiler
Explorer Authors` banner, using each file's **git creation year**
(added-at-this-path, so no `--follow` rename artifacts).

## Verification

- `check-license-headers` → clean (was 42 failures)
- `biome check` on all source → no fixes needed (banner format matches
existing convention)
- `tsc` backend + frontend + tests → clean
- pre-commit gauntlet (lint, ts-check, related tests: 528 passed) ran on
commit

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: mattgodbolt-molty <mattgodbolt-molty@users.noreply.github.com>
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-02 19:13:21 +01:00
CedricandMatt Godbolt b0726beb5f Fix Triton MLIR source locations (#8718)
## Summary
- resolve nested named MLIR location aliases in the MLIR asm parser
- strip MLIR location metadata from displayed device output
- make Device Viewer source colours and hover linkage use the owning
source editor

## Testing
- npm run test -- test/asm-parser-tests.ts --reporter dot
- npm run ts-check:frontend
- npm run ts-check:backend
- npm run ts-check:tests
- npx biome check lib/parsers/asm-parser-mlir.ts
test/asm-parser-tests.ts static/panes/device-view.ts
- git diff --check -- lib/parsers/asm-parser-mlir.ts
test/asm-parser-tests.ts static/panes/device-view.ts
- pre-commit hook: npm run lint, npm run ts-check, vitest related passed

Note: a standalone npm run test-min run failed in unrelated
test/demangler-tests.ts Rust demangling expectations in this local
environment.

---------

Co-authored-by: Matt Godbolt <matt@godbolt.org>
2026-07-02 18:52:31 +01:00
OfekandCopilot Autofix powered by AI 64b3ea2428 Optimizations in LLVM opt-pipeline (#8869)
3 Separate optimizations towards resolution of #8583:

1. (probably most substantial:) ``PrefixTree.replaceAll` did O(n^2)
allocations, causing substantial GC time:
```ts
const lineBit = line.substring(idxInOld);
const [oldValue, newValue] = this.findLongestMatch(lineBit);
```
For every character pos in a line this allocated a substring for the
entire remainder. Over one line that's O(n^2) bytes allocated, and
`processPassOutput` runs this on every line of every before/after IR
dump — which for an opt-pipeline run is enormous. This is a major
contributor to both the `replaceAll`/`processPassOutput` self-time and
the 20% GC.
Fix: make `findLongestMatch` accept a start offset and walk the existing
line string in place.

2. `JSON.stringify` large payloads once instead of twice, when caching
to S3

3. `processPassOutput` called `PrefixTree.replaceAll` which did a costly
build of replacement map but didn't use them. Now calls the new
`PrefixTree.replaceAllText`.



-------
The time measurements on the live site and on my machine differ
substantially. Before pursuing more aggressive optimizations I want to
check the impact of these, see if more work is needed.

One additional direction for (major) optimization: I think today each
pass dump is processed twice, once as 'before' and 2nd time as 'after'

---------
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
2026-06-26 22:10:36 +03:00
fa456a81f3 Fix #7870: use GCC pass-dump files to enumerate passes (#8826)
Following the discussion at #7870: `-fdump-passes` reports passes
enabled dynamically (e.g. loop2_unroll via `#pragma GCC unroll`) as OFF,
so they were missing from the pass dropdown although they were active.
Fixed by building the pass list from the dump files GCC actually wrote
instead.

While reworking this:
- Read all passes into a `passDumps` map shipped with the result, so
switching passes doesn't trigger a compile.
- Trim each dump to functions defined in the user's source, dropping
header/library functions; strip forced -lineno annotations from GIMPLE
(tree/IPA) dumps when Line Numbers is off, leaving RTL untouched.
- Exclude passes with empty output
- Add a GccDumpOutput type, backend unit tests and a cypress test.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

---------
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
2026-06-20 16:06:25 +03:00
6774d762ce Construct builtin examples source explicitly at startup (#8828)
Follow-up to #8779 (which fixed #8601, `builtin.sourcePath` being
ignored). Two related changes:

### 1. Construct the builtin source explicitly at startup (restore
fail-fast)

#8779 made the builtin "Examples" source read its config lazily, on the
first `list()`/`load()`. That fixed correctness but moved the failure
mode: a misconfigured `sourcePath` (missing/unreadable dir) no longer
fails at startup. The server boots, passes healthchecks, takes traffic,
and then throws on the first request that opens Examples.

This restores fail-fast by constructing the source explicitly once
configuration is loaded:

- Replace the `builtin` module-level singleton with a `BuiltinSource`
class whose constructor scans the examples directory, plus a
`createBuiltinSource()` factory that reads `builtin.sourcePath`.
- `lib/sources/index.ts` exposes `createSources()` instead of a
top-level `sources` array (a top-level array would re-run config reads
at import time, reintroducing #8601).
- `initialiseApplication` constructs the sources after config load and
passes the `Source[]` to `ClientOptionsHandler` and
`setupControllersAndHandlers` (both already accept injected sources).

A bad `sourcePath` now throws during startup, before the instance
reports healthy. The lazy fix's correctness (config read after
`initialize()`) is preserved.

### 2. Single source of truth for the examples path

`GolangParser` independently re-read `('builtin', 'sourcePath',
'./examples/')` to locate `go/default.go`, duplicating where the
examples directory is defined. Export `getExamplesRoot()` from
`lib/sources/builtin.ts` and use it in both `createBuiltinSource()` and
`GolangParser`, so the config key and default live in one place.
Behaviour is unchanged (same value resolved); it removes the drift risk
if the key or default ever changes.

### Tests
Tests construct `BuiltinSource` directly with a fixture directory (no
import-order/`resetModules` dance), cover the unknown-example path,
assert fail-fast on a non-existent dir, and verify
`createBuiltinSource()` reads the configured path.

- `npx vitest --run test/sources/builtin-tests.ts
test/compilers/argument-parsers-tests.ts`
- `npm run ts-check`
- `npm run lint-check`

---------

Co-authored-by: mattgodbolt-molty <mattgodbolt-molty@users.noreply.github.com>
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-14 22:38:23 +01:00
Puneet DixitandDeepak kudi 6f9f064a84 Fix builtin sourcePath configuration (#8779)
## Summary

- defer scanning builtin examples until `list()` or `load()` is called
- refresh the cached examples if `builtin.sourcePath` changes
- add a regression test that imports the builtin source provider before
properties are initialized, then verifies a custom `sourcePath` is used

Closes #8601.

## Tests

- `npm run test -- --run test/sources/builtin-tests.ts --reporter=dot`
- `npm run test-min -- --run test/sources/builtin-tests.ts
--reporter=dot`
- `npm run ts-check`
- `npx biome check lib/sources/builtin.ts test/sources/builtin-tests.ts
--write`
- `npm run lint-check -- lib/sources/builtin.ts
test/sources/builtin-tests.ts`
- `git diff --check`

Co-authored-by: Deepak kudi <deepakkudi23@adsl-172-10-9-116.dsl.sndg02.sbcglobal.net>
2026-06-14 22:02:37 +01:00
Nerixyz fab9e1f545 Use compiler's demangler type for LLVM IR (#8789)
The `LLVMIRDemangler` derived from `BaseDemangler`. It called the
demangler executable as-if it was `c++filt`. This would fail if the
demangler was `(llvm-)undname` (demangler for Microsoft names), because
it has a different output.

This PR refactors `LLVMIRDemangler` to take a demangler instance that it
calls into. `BaseDemangler` was extended to allow demangling a fixed set
of symbols and to skip applying the names. Both are needed for the IR
demangler. This way, the demangler instance can handle the details of
parsing the stdout and `LLVMIRDemangler` can provide the names and apply
the transforms.
2026-06-14 21:50:32 +01:00
05f59881f7 Make --tmp-dir authoritative over inherited environment (#8819)
Fixes #8816.

- `setupTempDir()` exports the configured dir as `TMPDIR`, `TMP` *and*
`TEMP`. POSIX `os.tmpdir()` consults `TMPDIR` first, so the old TMP-only
export meant an inherited `TMPDIR` silently defeated `--tmp-dir`
(verified empirically; prod was protected only by `sudo env_reset` in
start.sh). Setting all three also covers native Windows (`TEMP` > `TMP`
there) and WSL, and means spawned tools reading any of the variables
agree.
- Restores the `os.tmpdir() !== tmpDir → throw` sanity check from
613d7f688 (#6052), lost in the #7681 split refactor.
- The startup log now prints `os.tmpdir()` — the value that actually
matters — instead of `TEMP || TMP`, which printed `undefined` on a
default Linux run.
- The `lib/temp.ts` exit hook was `process.on('exit', async ...)`: exit
handlers can't await, so it never removed anything. Replaced with a
synchronous `cleanupSync()` (tested).
- Test hygiene fix that the work surfaced: the temp-dir tests restored
the environment by reassigning `process.env` wholesale; a replaced
`process.env` is a plain object whose writes never reach the real
environment, while `os.tmpdir()` reads the real environ via `safeGetenv`
— so the suite silently leaked env state across tests (and into any test
running later in the same worker). Now saves/restores the individual
variables.

The WSL `%TEMP%`-discovery-failure path (`wsl-vc.ts` parsing garbage on
fallback, #8816 item 4) is deliberately untouched — Windows-specific and
unverifiable here.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: mattgodbolt-molty <mattgodbolt-molty@users.noreply.github.com>
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-06-14 20:11:35 +01:00
19ae5abcf3 Count queue jobs as completed when they settle, not when dequeued (#8821)
The last loose end from the incident issue —
`ce_compilation_queue_completed_total` incremented in a `finally` that
ran as soon as the job *returned its promise*, so it counted dequeues,
in lockstep with `ce_compilation_queue_dequeued_total`, and
`status().running` was almost always 0.

Completion is now counted when the job settles (fulfilled or rejected),
via a settlement callback rather than by awaiting in the wrapper. The
non-awaiting detail matters: my first attempt awaited `job()` so the
`finally` ran at settlement — and the existing "times out a job that
never settles" test immediately caught that this keeps `_running`
populated forever for a wedged job, reintroducing the exact
`busy`-forever wedge #8813 fixed. (A nice demonstration of that test
paying for itself.) With the callback approach, a never-settling job
correctly never counts as completed, so `dequeued − completed` now
exposes wedged/in-flight jobs — which would have made the original
incident visible directly in Grafana.

New test pins the semantics: counter unchanged while a job is running,
+1 once it settles.

Per discussion: no temp-dir sweeps of any kind (instances are replaced,
never restarted; and multiple CE processes may share a machine), so the
orphaned-dirs observation in #8811 is closed as won't-fix.

Closes #8811.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: mattgodbolt-molty <mattgodbolt-molty@users.noreply.github.com>
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-06-11 23:02:35 +01:00
51317dc13f Cap conan package extraction size; require http(s) package URLs (#8820)
Fixes #8817. Kept deliberately simple per discussion — the conan server
is CE's own infrastructure, so these are hygiene bounds, not attack
mitigations:

- A generous fixed 2GiB cap on the total declared size of extracted
files (tar-stream enforces entry bodies match their headers, so summing
`header.size` bounds bytes written). Real packages are tens to a few
hundred MiB; hitting this means a packaging error or a corrupt/bombed
archive, and the extraction rejects cleanly through the existing error
path.
- The package URL conan returns must be http(s). No redirect
restrictions (conan may legitimately hand out redirecting/presigned
URLs), no config plumbing.

Both paths tested (cap exercised by lowering the limit on the instance
under test; scheme via a `file://` URL).

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: mattgodbolt-molty <mattgodbolt-molty@users.noreply.github.com>
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-06-11 22:25:07 +01:00
8e6033825a Fail healthcheck when temp filesystem free space is low (#8814)
Part of #8811 (production disk-full incident).

During the incident `/healthcheck` stayed green for hours while every
compilation failed with ENOSPC: the empty-job queue check passed (one of
two queue slots still worked), and the EFS health-file read doesn't
touch the root filesystem — so the load balancer never replaced the
instance.

This adds a free-space check on the filesystem where compilation temp
dirs are actually created: `lib/temp.ts` gains `getTempRoot()`, used
both by `temp.mkdir()` and the healthcheck, so the two can't drift
apart. (That resolves via `os.tmpdir()`; `--tmp-dir` flows into it as
`$TMP` via `setupTempDir()` — `/nosym/tmp` in prod.) Below the threshold
the healthcheck returns 500 and the load balancer replaces the instance
*before* hard failure. A `statfs` failure is itself treated as
unhealthy.

Configuration: `healthCheckMinFreeSpaceMiB` — required constructor
argument (no code default, per review); `amazon.properties` sets 2048
(at the incident's ~300MB/min fill rate that gives the LB several
minutes to act); the ceProps fallback is 100 for unconfigured/local
instances; 0 disables the check.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: mattgodbolt-molty <mattgodbolt-molty@users.noreply.github.com>
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-06-11 22:01:53 +01:00
a80b7eb210 Fix hang and uncaught exception when conan download is severed mid-stream (#8812)
Part of #8811 (production disk-full incident).

## The incident bug

If a conan library package download's connection died mid-transfer,
`downloadAndExtractPackage()`:

- threw an **uncaught exception** (`TypeError: terminated`): the error
was emitted on the `Readable.from(res.body)` wrapper, which had no
`'error'` listener — `.pipe()` neither attaches nor forwards one;
- **never settled its promise**: gunzip/tar saw neither an error nor an
end, so neither `resolve` nor `reject` was ever called. This wedged a
compilation queue slot forever, which permanently disabled temp dir
cleanup (it only runs when the queue is idle) and filled the disk on
prod.

The download path is rewritten around `stream.pipeline()`, which
propagates errors through every stage and guarantees settlement.
Per-entry file writes also go through `pipeline()`, so write errors
propagate (via `extract.destroy`) instead of being silently dropped, and
`next()` fires after the file is fully flushed rather than on stream
`'end'`.

## Extraction hardening (from review + an adversarial security pass)

- **Zip-slip guard anchored at the per-library extraction root**
(`downloadPath/<libId>`; plain `downloadPath` for `extractAllToRoot`): a
package can no longer write over a sibling library's files or the
compilation's own. The check is `path.relative`-based — immune to prefix
collisions (`/tmp/pkg` vs `/tmp/pkg-evil`) and to directories merely
*named* with leading dots.
- **Only regular-file entries are ever written**: directories, symlinks,
hardlinks and other types are drained and skipped, including malformed
entries (e.g. a directory claiming non-zero size) whose body could
otherwise land on disk as a file. CE never creates links of any kind;
prod additionally runs under the `/nosym/tmp` nosymfollow mount.
- **Zero-length files extract correctly** (the pre-pipeline code created
them as a side effect of an early `createWriteStream` — with a leaked
fd; the first pipeline version dropped them entirely).
- **Logs preserve stacks** (error objects passed to winston, not
interpolated) and the archive-controlled entry name is JSON-stringified.

Deliberately out of scope (filed as #8817): decompressed-size caps and
`packageUrl` scheme/redirect validation — defense-in-depth against our
own conan server, not blockers. See the review-convergence comment below
for vectors evaluated and rejected with rationale.

## Tests

`test/buildenvsetup-ceconan-tests.ts` (new), against a local HTTP
server:
- **Severed mid-stream download rejects rather than hanging** — against
the pre-fix code this reproduces the production failure exactly
(unhandled `TypeError: terminated` + timeout).
- Happy-path extraction including a zero-length file.
- 404 → rejection.
- Zip-slip: full escape and sibling-library escape are skipped; a
`..`-named directory inside the library root still extracts.
- A malformed sized-directory entry settles (no wedged promise) and
writes nothing.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: mattgodbolt-molty <mattgodbolt-molty@users.noreply.github.com>
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-06-11 22:01:24 +01:00
9db0c4d28b Make compilation queue timeout effective; exit on uncaught exceptions (#8813)
Part of #8811 (production disk-full incident). Companion to #8812 — this
is the systemic backstop so no future never-settling job can wedge the
system.

Two changes:

**Queue timeout was dead config.** `enqueue()` passed `timeout:
undefined` to p-queue's `add()`; p-queue spreads per-call options over
its defaults, so this overrode and *disabled* the queue-wide timeout
configured from `compilationEnvTimeoutMs` (default 300s). A job whose
promise never settled therefore occupied a queue slot forever — and
since temp dir cleanup only runs when the queue is fully idle, one
wedged slot permanently disabled cleanup and filled the disk. Removing
the override makes the timeout effective: in p-queue v9 a timed-out task
rejects with `TimeoutError`, freeing the slot. (The timeout doesn't kill
underlying work — that remains the exec layer's job — but the system
makes progress again.)

**Uncaught exceptions now actually stop the process.** The handler set
`process.exitCode = 1` assuming the app would "exit naturally", but a
process with live server listeners never does: during the incident the
instance limped on half-dead for hours, passing healthchecks while every
compilation failed. Now it exits after a 1s delay (letting winston flush
its transports), and the load balancer replaces the instance.

The new queue test fails against the previous code: a never-settling job
is never rejected and `status().busy` stays true forever. Also adds
basic enqueue/nested-enqueue coverage.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: mattgodbolt-molty <mattgodbolt-molty@users.noreply.github.com>
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-06-11 21:58:07 +01:00
Patrick Quist c432fcc478 feat: lazy-load languages, compilers, libraries, and tools from API (#8549) 2026-06-05 15:54:27 +02:00
532b6c2b57 Fix #8695: [LANGUAGE REQUEST]: Add lua as a supported language (#8696)
Automated fix by @leftibot.

### What changed

> Fix #8695: add Lua as a supported language
> Add support for Lua via the reference PUC-Rio interpreter. Disassembly
is
> produced by `luac -l -l -p`, which writes a verbose bytecode listing
to
> stdout that the LuaCompiler captures and writes to the output file.
The
> class exposes overridable hooks (`resolveLuacExe`,
`getDisassemblyArgs`)
> so alternative implementations such as LuaJIT can plug in a different
> bytecode dumper without rewriting the compiler. Production config
ships
> five Lua releases (5.1.5, 5.2.4, 5.3.6, 5.4.7, 5.5.0) covering the
> actively used minor versions.

### Files
```
 etc/config/lua.amazon.properties   |  27 ++++++
 etc/config/lua.defaults.properties |   5 +
 examples/lua/default.lua           |   5 +
 lib/compilers/_all.ts              |   1 +
 lib/compilers/lua.ts               | 182 +++++++++++++++++++++++++++++++++++++
 lib/languages.ts                   |  11 +++
 test/lua-tests.ts                  | 138 ++++++++++++++++++++++++++++
 types/languages.interfaces.ts      |   1 +
 8 files changed, 370 insertions(+)
```

Closes #8695

_Triggered by @lefticus._

---------

Co-authored-by: leftibot <leftibot@users.noreply.github.com>
Co-authored-by: Matt Godbolt <matt@godbolt.org>
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-03 22:45:23 -05:00
Rayan Salhabandcyphercodes 5a674bbc5c Fix c2rust output location parsing (#8768)
## Summary

Fixes #8709.

This tightens the generic `file:line` parser so c2rust AST dump lines
like `CTypeId(42): Located {` are left as plain output instead of being
interpreted as source diagnostics.

## Test plan

- `npm test -- test/utils-tests.ts`
- `npm run lint-check -- lib/utils.ts test/utils-tests.ts`
- `npm run ts-check:tests`
- `npm run ts-check:backend`
- `git diff --check`

---------

Co-authored-by: cyphercodes <cyphercodes@users.noreply.github.com>
2026-06-03 21:25:50 -05:00
Matt GodboltandClaude Opus 4.8 885a5b8d8e Fix flaky Windows exec timeout test (#8765)
## Problem

The Windows variant of the `Execution tests > Executes external commands
> handles timeouts` test (`test/exec-tests.ts`) is flaky on CI. It ran:

```ts
exec.execute('powershell', ['-Command', '"sleep 5"'], {timeoutMs: 10})
```

The embedded double-quotes make `"sleep 5"` a **string literal** that
PowerShell just echoes and exits immediately — it never sleeps. The test
only "passed" by racing the 10 ms timeout against PowerShell's startup.
When PowerShell wins the race it returns `code: 0` / `stdout: "sleep 5"`
instead of the expected killed result, intermittently failing the
Windows `test` job.

(Spotted while verifying CI on #8737 — the only failure there was this
test, unrelated to that PR.)

## Fix

Use `Start-Sleep -Seconds 5`, which actually blocks, so the 10 ms
timeout deterministically kills it. The expected result block is
unchanged (`code: 1` is what `taskkill` yields for an externally-killed
process on Windows). Added a comment explaining the rationale, and fixed
the `timouts` → `timeouts` typo in both the Windows and POSIX test
names.

## Testing

- POSIX branch runs locally: `npx vitest run test/exec-tests.ts` → 22
passed.
- The Windows branch can only run on a Windows runner; the change is
confined to the command string and leaves the assertion identical.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-01 17:43:25 -05:00
Ofek 1b2bb4706e Fix #8740: Remove outdated security check (#8752) 2026-05-28 20:45:19 +03:00
Ofek f162fa265a Fix #8563: python bytecode basic-block parsing fixes (#8736)
Before:
<img width="1642" height="547" alt="image"
src="https://github.com/user-attachments/assets/ef37ebd5-cfe4-43a6-8ea0-c08dc32f0b8f"
/>


After:
<img width="1747" height="711" alt="image"
src="https://github.com/user-attachments/assets/99a7bcdb-9500-4095-a028-76e80b4c8e0f"
/>

---------
2026-05-23 15:25:52 +03:00
Steve 156f4b3542 Implement source mapping for .NET compilers (#8666)
This PR implements the source mapping for .NET compilers (C#, F#, VB.NET
and IL), supports CoreCLR, Crossgen2 and NativeAOT compilers.

- Add a parser that walks ECMA-335 metadata and Portable PDB sequence
points to build IL-offset-to-source mappings for .NET methods
- Load PDBs emitted by the .NET compiler after building the dll, and
then save the source mapping in the result
- Extend the .NET asm parser to match disassembly method signatures,
including generic types, generic methods, and inline root offsets, so
emitted asm lines inherit the correct source locations
- Use debug info emitted by the JIT `INLRT @ 0x##` as anchors to match
the offset

Showcase:


![image1](https://github.com/user-attachments/assets/5309fe70-be87-4f94-b70c-21bb91f745be)


![image2](https://github.com/user-attachments/assets/9d15741e-08ff-4f20-8a32-efa0d8307dea)
2026-05-10 09:15:36 -05:00
8891949f71 MCP: list_libraries version-string match + HPPA/Go cross-compiler instructionSet retags (#8688)
## Summary

Three related fixes prompted by driving the deployed MCP endpoint after
#8644 / #8685 merged:

1. **`list_libraries` match also searches version strings.** The natural
LLM query "find Boost 1.88" returned zero results —
`list_libraries({language:"c++", match:"boost 1.88"})` only matched
against `{id, name}`, so the version token never matched anything.

2. **HPPA + Go cross-compiler `instructionSet` retags.** Discovered via
`list_compilers(match="gcc 16", instructionSet="amd64")` returning
*only* `hppag1610` (HPPA cross-compiler) and missing plain `g161`
(x86-64 GCC). Two layered causes — HPPA had no entry in
`InstructionSetsList`, so the heuristic in `lib/instructionsets.ts`
defaulted HPPA cross-compilers to `amd64`; and 12 Go cross-compiler
groups (`386gl`, `arm32gl`, `arm64gl`, `mips*gl`, `ppc64*gl`, `riscvgl`,
`s390xgl`, `wasmgl`) had never been tagged at all.

3. **Defensive bucketing in MCP `pickLatest`.** Belt-and-braces fix:
bucket key is now `(lang, instructionSet, group)` so different compiler
families that happen to share an arch tag can't fight for the same
`latestPerMajor` slot.

## Changes

- `lib/mcp/tools/libraries.ts` — extend `applyMatch` haystack to include
`versions[].version` (human form, e.g. `"1.88.0"`) and `versions[].id`
(e.g. `"188"`).
- `lib/mcp/tools/compilers.ts` — `pickLatest` bucket key now includes
`c.group`.
- `types/instructionsets.ts` + `lib/instructionsets.ts` — new `'hppa'`
entry.
-
`etc/config/{ada,c++,c,d,fortran,gimple,objc++,objc}.amazon.properties`
—
`group.<gnathppa|gcchppa|cgcchppa|gdchppa|gimplehppa|objcppgcchppa|objchppa>.instructionSet=hppa`.
- `etc/config/go.amazon.properties` — explicit `instructionSet=` for all
13 Go arch groups (12 cross + amd64gl for symmetry).
- `test/mcp/mcp-tests.ts` — covers the bucketing-by-group case.
- `test/instructionsets-tests.ts` — covers the hppa target-string
branch.

## Follow-up

#8690 — drop the `lib/instructionsets.ts` path-based heuristic entirely
in favour of required `instructionSet` properties (the path branch is
Amazon-install-specific and silently mistags compilers on any non-Amazon
layout).

## Test plan

- [x] `npm run test -- --run mcp` — passes (existing + 2 new)
- [x] `npm run test -- --run instructionsets` — passes (existing + 1
new)
- [x] `npm run test:props` — 90/90 pass
- [x] `make pre-commit` — exits 0
- [ ] Drive the staging endpoint with `list_libraries({language:"c++",
match:"boost 1.88"})` and confirm Boost is returned with its versions.
- [ ] Drive the staging endpoint with `list_compilers({match:"gcc 16",
instructionSet:"amd64", latestPerMajor:true})` and confirm `g161`
(x86-64) appears and `hppag1610` does not.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: mattgodbolt-molty <mattgodbolt-molty@users.noreply.github.com>
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-09 17:14:30 -05:00
312846230a Add built-in MCP endpoint for LLM tool integration (#8644)
Expose Compiler Explorer's compile, list, shortlink and asm-docs APIs
via a Model Context Protocol (MCP) endpoint mounted at `/mcp`. This lets
MCP-aware clients (Claude, etc.) drive CE directly as a tool.

## Tools exposed at `/mcp`

- **`compile`** — compile source and return assembly / stdout / stderr,
with optional execution.
- `compiler` is **optional**; falls back to the language's
`defaultCompiler` from `list_languages` ("compile this hello world in
C++" is one call).
- `libraries[].version` accepts **either** the version id (`"188"`) or
the human form (`"1.88.0"`) — both work.
- When `execute: true` and the build fails,
`buildResult.stdout`/`stderr` carry the real compiler diagnostics with
**ANSI codes stripped** so an LLM caller sees clean text.
- Caps: `maxAsmLines` / `maxStdoutLines` / `maxStderrLines` with
truncation flags + total counts.
- **`list_compilers`** — with `language`, `instructionSet` (closed enum
from `InstructionSetsList`), `match` (case-insensitive AND-of-tokens;
numeric/dotted-version tokens treated as version-prefix), `lean: true`,
`maxResults`, `latestPerMajor: true`, and `includeExperimental: true`.
- Hard cap of 200 entries on lean responses with a refinement hint —
prevents the unfiltered call from overflowing.
- Each entry exposes `releaseTrack` (`stable | nightly | prerelease |
experimental`) and `supportsExecute` / `supportsBinary`.
- **`list_libraries`** — with `match`, `lean`, `maxResults` (same
lean-cap behaviour).
- **`list_languages`** — minimal listing including `defaultCompiler` and
`compilerCount` per language.
- **`generate_short_url`** — returns `{url}`. Library versions are
normalised before saving.
- **`get_shortlink_info`** — returns saved sessions in the **same shape
`compile` accepts** (`{compiler, options, libraries:[{id, version}]}`)
for direct round-tripping. Multi-pane shortlinks (executors,
conformance, CMake trees) are flattened to the basic compile inputs.
- **`lookup_asm_instruction`** — `instruction_set` is a closed enum
derived from the registered providers (no hand-listed enum values; one
source of truth in `lib/asm-docs/`).

## Implementation

- New `lib/mcp/` module wiring `@modelcontextprotocol/sdk` into the
existing Express router via `StreamableHTTPServerTransport` (stateless
mode — one server per request).
- `lib/mcp/utils.ts`: tokenised `match` with version-prefix matching for
numeric/dotted-version tokens (so `"gcc 14.1"` matches `"gcc 14.1"` and
`"gcc 14.1.0"` but NOT `"gcc 14.10"` or `"gcc 14.0.1"`); `applyCap` with
both per-call lean degradation and an absolute hard cap; `truncateLines`
strips ANSI escapes via the existing `filterEscapeSequences` helper from
`lib/utils.ts`.
- `lib/mcp/library-utils.ts`: `normaliseLibraryVersion` and
`normaliseRequestLibraries` — single source of truth for "accept id or
human version" semantics, used by both `compile` and
`generate_short_url`.
- Schema descriptions are tight (LLM context cost matters) and derive
closed-set enums programmatically from `InstructionSetsList`,
`RELEASE_TRACKS`, and a new `availableAsmDocsKeys` export — no
hand-listed values that can rot.
- Refactor `StorageBase` static helpers (`encodeBuffer`, `isCleanText`,
`getSafeHash`) to module-level functions with type-checked input so MCP
tools can build shortlink hashes without instantiating a storage
backend.
- Expose `ApiHandler.compileHandler` and split out
`getAvailableLanguages()` so MCP can reuse the same code paths the REST
API uses; new `ApiHandler.getDefaultCompilerFor()` for the
compile-default-compiler resolution.
- Browser-friendly CORS on `/mcp`: OPTIONS preflight advertises
`Access-Control-Allow-Methods: POST, OPTIONS` (the shared `cors`
middleware doesn't set Methods); 405 responses on other verbs use the
same Allow header.
- `docs/API.md`: clarify that `/api/shortener` requires a JSON object
body (the prior docs implied but didn't state it).

## Tester feedback addressed

A Claude tester drove the staging deployment through several rounds;
full thread in PR comments. Round-by-round refinements:

- Compile diagnostics surfaced on execute-mode build failures (the
original "silent `Build failed` with empty stderr" bug).
- `execute: true` schema description rewritten to reflect the actual
behaviour.
- Library `version` accepts both forms; clean errors when neither
matches with a sample of available versions.
- `latestPerMajor` rebuilt on top of the `releaseTrack` field added in
#8685, with `includeExperimental` opt-in for c++ proposal forks.
- Lean mode (`lean: true`) for catalog browsing, plus a hard 200-item
cap so even unfiltered calls don't overflow the host.
- Tokenised `match` with version-prefix semantics for
numeric/dotted-version tokens. **Behaviour change** vs the old
`/api/compilers?fields=...` text matching: bare numeric tokens are now
treated as version segments — `"2024"` no longer substring-matches
inside `"v2024beta"`, and `"14.1"` no longer wrongly matches `"14.0.1"`.
Strict improvements but worth a release-note line for callers depending
on the prior loose behaviour.
- ANSI escape code stripping from compile output.
- `instructionSet` as a structured filter (instead of relying on `match`
strings).
- `supportsExecute` / `supportsBinary` on `list_compilers` so an agent
knows whether `execute: true` will work without trying.
- `compilerCount` per language so an agent can tell well-stocked vs
niche languages at a glance.
- Compiler-not-found / library-not-found errors point at the right
`list_*` tool.

## Depends on

#8685 (releaseTrack metadata on `CompilerInfo`) — merged.

## Test plan

- [x] `npm run test -- --run mcp release-track` — all pass (78 + 22)
- [x] `npm run test-min` — full minus expensive, all green
- [x] `make pre-commit` — exits 0
- [x] Multi-round driving on staging via the live MCP endpoint,
including: default-compiler hello-world (no compiler arg), human-form
library version (`"1.88.0"`), broken-compile-with-execute (verifies
buildResult), compile+run with stdin, compile+library Boost 1.90,
parallel `-O0` vs `-O3` diff, `list_compilers latestPerMajor` for
c++/rust/go/csharp, `list_libraries match boost/fmt/json`,
`lookup_asm_instruction MOV amd64`, full `generate_short_url` →
`get_shortlink_info` → re-`compile` round-trip with library
normalisation.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Matt Godbolt <mattgodbolt@hudson-trading.com>
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Co-authored-by: mattgodbolt-molty <mattgodbolt-molty@users.noreply.github.com>
2026-05-08 10:50:09 -04:00
37f73b9b67 Add releaseTrack metadata to CompilerInfo (#8685)
## Summary

Adds a structured `releaseTrack: 'stable' | 'nightly' | 'prerelease' |
'experimental'` field on `CompilerInfo` so consumers can distinguish
release tracks that aren't currently separable from the existing
`isSemVer` / `isNightly` / `semver` fields.

Today every compiler with a non-numeric semver and `isNightly=true`
looks the same from the outside: Rust nightly, Rust beta, gcc snapshot,
and gcc's various experimental forks (`gcontracts-trunk`,
`gcc-modules-trunk`, `glambda-p2034-trunk`, ...) all share the same
shape. Anything that wants to ask "what's the canonical newest build of
language X" — a UI badge, the upcoming MCP `latestPerMajor` knob
(#8644), etc. — has no way to tell those apart.

## Implementation

- **Heuristic** in `lib/release-track.ts` driven by `asSafeVer` + the
existing `isSemVer`/`isNightly` flags. Real semvers with a prerelease
segment (e.g. micropython `1.28.0-preview`) are flagged `prerelease`;
semvers containing `trunk`/`main` and the literal `nightly` tag go to
`nightly`; bare `beta`/`alpha`/`rc` tags go to `prerelease`; `isNightly`
with anything else (the c++ experimental forks) goes to `experimental`;
everything else stays `stable`.
- **Override:** `compiler.releaseTrack=` / `group.releaseTrack=` in
`.properties` for cases the heuristic can't reach from structural
fields. Used here for `rustccggcc-master` / `mrustc-master`, where
"master" lives in the compiler id but not the semver field.
- **Backfill** in `loadPrediscovered()` so cached discovery JSON written
before this field existed doesn't break, and so a hand-edited invalid
value gets re-inferred rather than violating the type contract.
- **Tests:** 18 unit tests covering each rule + edge cases (whitespace,
mixed case, prerelease segments) and the `isReleaseTrack` type guard.

## API exposure

`releaseTrack` is on `CompilerInfo` so it appears via
`/api/compilers?fields=all`. It is **not** in the default field set, so
existing API responses are unchanged. UI consumers can opt in.

## Why this is a separate PR

This started as a piece of #8644 (MCP endpoint) — the MCP
`list_compilers` `latestPerMajor` knob needs this distinction to give
clean answers ("newest GCC" should not return a sea of experimental
forks). Rather than hack around the missing metadata in just the MCP
layer, the metadata belongs at the source where other features (UI
badging, etc.) can consume it. #8644 will rebase on top of this.

## Test plan

- [ ] `npm run test -- --run release-track` — 18/18 pass
- [ ] `npm run test:props` — 90/90 pass
- [ ] `make pre-commit` — exits 0 (pre-existing warnings only)
- [ ] Manual sanity check on staging:
`/api/compilers/c%2B%2B?fields=all` returns `releaseTrack` for each
compiler

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: mattgodbolt-molty <mattgodbolt-molty@users.noreply.github.com>
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-07 19:26:03 -04:00
Matt Godbolt (bot acct)andmattgodbolt-molty f3e27510f6 Stop bronto-refactor stdout being tagged as fake diagnostics (#8680)
## Summary

bronto-refactor emits the refactored source on stdout. The default
`parseOutput` pipeline includes a `FileWithLineMessage` matcher whose
regex (`SOURCE_WITH_FILENAME` in `lib/utils.ts`) is permissive enough to
mistake any C++ member call with a numeric first argument — e.g.
`r.fetch_add(2, std::memory_order_relaxed);` — for a `filename:line:`
reference, treating `r.fetch_add` as a filename and `2` as a line
number. The result was fake red error squigglies in the editor, with the
trailing `, std::memory_order_relaxed);` shown as the diagnostic
message.

`BrontoRefactorTool` now overrides `parseOutput` to drop
`FileWithLineMessage`. `SourceWithLineMessage` is kept so genuine
`<source>:N:M:` diagnostics on stderr still surface.

Reported via the web UI when running bronto-refactor on this:

```cpp
#include <atomic>
void foo(std::atomic<int>& r) {
    r.fetch_add(2, std::memory_order_relaxed);
    r.fetch_add(4, std::memory_order_relaxed);
}
```

## Out of scope

The `SOURCE_WITH_FILENAME` regex in `lib/utils.ts:154` is genuinely too
loose — any tool whose stdout is source-like (formatters, refactorers)
can hit this. Tightening it (require an extension, or `:`-only
separator) is a separate change since it touches every compiler/tool
that relies on `parseOutput`.

## Test plan

- [x] Added `test/tool-tests.ts` case asserting refactored source
produces no tags.
- [x] Added a second case asserting a real `<source>:N:M:` diagnostic on
stderr is still tagged (so we didn't over-blunt the parser).
- [x] Verified the first test fails on `main` and passes with the fix.
- [x] `npm run ts-check`, `npm run lint`, `npm run test -- --run
tool-tests` all pass.
- [ ] Confirm in the web UI that the original repro no longer shows
squigglies.

cc @fowles

Co-authored-by: mattgodbolt-molty <mattgodbolt-molty@users.noreply.github.com>
2026-05-06 14:27:27 -04:00
8918aae56c Add asm docs for RISC-V SGT/SGTU pseudoinstructions (#8627)
## Summary
- Fixes #8622: adds assembly documentation entries for the RISC-V `sgt`
and `sgtu` pseudoinstructions so the hover/"View assembly documentation"
feature works instead of showing an error.
- `sgt rd, rs, rt` expands to `slt rd, rt, rs`; `sgtu rd, rs, rt`
expands to `sltu rd, rt, rs`. Entries follow the same shape as the
existing `SGTZ` pseudo entry.

## Test plan
- [x] `npx vitest run test/handlers/asm-docs-tests.ts`
- [x] `npx tsc --noEmit`
- [x] `npm run lint` (no new errors)

---

This PR is authored by an LLM (Claude) acting on behalf of @mattgodbolt.

---------

Co-authored-by: mattgodbolt-molty <mattgodbolt-molty@users.noreply.github.com>
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-14 21:32:23 -05:00
Patrick Quist ee3e261bb3 Make libs= property optional via auto-discovery (#8552) 2026-03-11 21:40:54 +01:00
Patrick QuistandClaude Opus 4.6 305156c0a4 fix: allow plus signs in property key names and values (#8485)
## Summary
- Fixes the property parser regex to allow `+` in key names (e.g.
`abc+def=etc`)
- The regex from #8387 used `[^=+]+` for key matching, which excluded
`+` from key names entirely
- Changed to a lazy `.+?` match so `+` is only treated as the `+=`
operator when immediately before `=`

This is a small targeted fix and does not address all edge cases with
the `+=` syntax.

## Test plan
- [x] Added test: `abc+def=etc` correctly sets key `abc+def` to `etc`
- [x] Added test: `abc=def+ghi` correctly sets key `abc` to `def+ghi`
- [x] All existing `+=` append tests continue to pass

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-27 21:10:47 -05:00
Jonathan Coates e21749ea2b Update labelReference regex to match LLVM IR syntax (#8491)
A `catchswitch` instruction has the form:

    catchswitch within none [label %catch.start] unwind to caller

The LLVM IR parser then extracts the labels out of this expression.
However, the regex is too greedy, and (incorrectly) matches
`%catch.start]`. We update the regex to match what LLVM's lexer does.
The [language reference](https://llvm.org/docs/LangRef.html#identifiers)
states that quoted identifiers can include `\xx` escapes, however as far
as I can tell [that is *not*
true](https://github.com/llvm/llvm-project/blob/413cafa4624eb37e586e266f44abd64896e1c598/llvm/lib/AsmParser/LLLexer.cpp#L391-L421),
so I have elected not to support them.

For the following program (targetting WASM, compiled with
`-fwasm-exceptions`):

```c
void bar(int x);

void foo() {
    try {
        bar(1);
    } catch(int x) {
    }
}
```

**Before:**

<img width="1492" height="411" alt="A CFG of the above program. The
catch block is entirely disconnected from the main part of the graph."
src="https://github.com/user-attachments/assets/ad9038cc-f372-4109-bc25-328537bcea88"
/>

**After:**

<img width="1286" height="639" alt="A CFG of the above program. The
catch block is now correctly connected to the rest of the graph."
src="https://github.com/user-attachments/assets/27cce7b3-dd67-4c1c-928c-93f7eaa53fa2"
/>
2026-02-27 20:59:37 -05:00
Blake Ledden 05f60761ad Remove unused AsmResultLink type and links field (#8365)
The `links` field in `ParsedAsmResultLine` and the `AsmResultLink` type
have been unused since 2019 when clickable address links were replaced
by the labels system. This just removes the dead code.

Closes #8251
2026-02-27 20:49:32 -05:00
Matt Godbolt (bot acct)andmattgodbolt-molty 20505fba5a Filter NVCC fatbinData label from assembly output (#8506)
*(I'm Molty, an AI assistant acting on behalf of @mattgodbolt)*

Closes #5178

## Problem

NVCC embeds the CUDA fat binary blob in the host-side x86 assembly
inside a `#APP`/`#NO_APP` inline-assembly block, under a label called
`fatbinData`. In a realistic kernel this can be 100+ lines of `.quad`
hex values — a wall of noise before any user-readable code.

Example: https://godbolt.org/z/W3YMcq8oY

## Fix

Per-compiler pre-processing step in `NvccCompiler.processAsm()`: before
the host assembly reaches the ASM parser, any `#APP`/`#NO_APP` block
containing a `.nv_fatbin` section is stripped out entirely.

- Only `.nv_fatbin` blocks are removed; genuine user inline-assembly
blocks (which also use `#APP`/`#NO_APP` but without `.nv_fatbin`) are
left intact.
- Intentionally NVCC-specific — no changes to the base `AsmParser`, no
false-positive risk for other compilers.
- Stripping happens before `findUsedLabels` runs, so `fatbinData`
naturally disappears as unreferenced without any special-casing in the
parser's label-filtering logic.
- Gated on the existing Labels filter: with no filters active everything
remains visible; with Labels on the blob disappears.

## Testing

**New compiler unit tests** (`test/compilers/nvcc-tests.ts`):
- Strips `#APP`/`#NO_APP` blocks containing `.nv_fatbin`
- Preserves `#APP`/`#NO_APP` blocks without `.nv_fatbin` (user inline
asm)
- Handles multiple mixed blocks correctly
- No-op when no `#APP` blocks present
- Gracefully handles malformed unclosed blocks

**New parser filter-case**
(`test/filters-cases/nvcc-x86-host-example.asm`): representative NVCC
12.0 host assembly (real 15-line fat binary, boilerplate functions,
`.nvFatBinSegment` section) with nine filter-combination snapshots
documenting parser behaviour in isolation. These correctly show that the
**base parser itself does not filter `fatbinData`** — that's the
compiler pre-processor's job.

All 767 tests pass.

Co-authored-by: mattgodbolt-molty <mattgodbolt-molty@users.noreply.github.com>
2026-02-22 19:46:36 -06:00
Matt Godbolt (bot acct)andmattgodbolt-molty 54572dfa4d Add LLVM IR filters for declarations and library function thunks (#8503)
Closes #6319
Closes #6320

Adds two new opt-in filter checkboxes to the LLVM IR view's **Filters**
dropdown:

### Hide Declarations (off by default)
Filters external function declaration lines (lines starting with
`declare`). These are forward declarations of external functions and are
often noise when focusing on user code.

**Off by default** — as noted in #6319, `declare` lines are part of
valid IR and are needed when copying output into other tools such as
`opt`, `llc`, `alive2`, etc.

### Hide Library Functions (off by default)
Filters compiler-generated library function thunks — specifically
function definitions whose name matches patterns like `@jfptr_*` (used
by Julia). These are boilerplate wrapper functions that aren't useful
when reading IR.

**Off by default** for the same reason — these are real function
definitions in the IR.

Both filters follow the same pattern as existing IR filters (debug info,
metadata, attributes, comments). Unit tests added in
`llvm-ir-parser-tests.ts` covering filter-on, filter-off, and
preservation of unaffected lines.

*(I'm Molty, an AI assistant acting on behalf of @mattgodbolt)*

---------

Co-authored-by: mattgodbolt-molty <mattgodbolt-molty@users.noreply.github.com>
2026-02-22 17:25:36 -06:00
Matt GodboltandClaude Opus 4.6 624c5c026e Update npm dependencies and fix tom-select type import (#8477)
Inline the escape_html type instead of importing from tom-select's
internal dist/types/ path, which was removed in v2.5.1. The type is just
(str: string) => string, so there's no need to depend on the package's
internal file layout.

Also fix missing iframe title attributes in test/embedding.html.

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-16 15:12:07 -06:00
Erik HemmingandPatrick Quist 97233932f1 Add m68k asm parser to handle | comment character (#8469)
m68k GAS uses `|` as the comment character instead of `#`.
The base asm parser doesn't recognise this, so inline asm source
location markers (e.g. `| 2 "file.c" 1`) leak through into the output
instead of being filtered.

Repro on godbolt.org: https://godbolt.org/z/vYneWc8Tf

---------

Co-authored-by: Patrick Quist <partouf@gmail.com>
2026-02-16 14:01:37 -06:00
narpfel c4c0ad4c8b [llvm-ir]: Filter empty metadata nodes (#8473)
LLVM IR specialised metadata nodes can have no arguments, e. g.
[`DIAssignID`](https://llvm.org/docs/LangRef.html#diassignid), which is
commonly emitted by `clang` (https://godbolt.org/z/rb19oGMoT).

These were not filtered because the regex required at least one
character in the field list.
2026-02-16 10:38:21 -06:00