Send Compile & run through a CompileBackend instead of straight to godbolt
Every compile went to godbolt.org from the session directly. The roadmap moves compiles, and later Dafny and Lean checks, to a pinned service of the app's own, and godbolt has no service guarantee, so where a compile goes is now one replaceable piece. - src/services/compile-backend.ts: a CompileBackend (id, host, compiler, compile), explorerBackend() for any service that speaks Compiler Explorer's API at a base URL, GODBOLT as the default, and compileBackend() / setCompileBackend(). - godbolt.ts: compileMojo takes a CompileTarget (base, compiler, host) and names that host in its messages; the request body is unchanged, so tests/mojo.test.mjs still holds it to what the corpus pipeline sends. - Session.compile asks the current backend and records which host answered (CompileRecord.host; older records came from godbolt.org). - The Compiler view names the host it is asking and the host that answered. The "Compiled on godbolt" badge keeps its wording until a second backend is deployed. A test sends a compile through a fake backend and a refused local address. Manual check list: open a Mojo exercise in the Developer area, Compile & run, and see "Asking godbolt.org (mojo_1_1_0)…" then "Mojo 1.1.0 on godbolt.org" in the Compiler view. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01FgvbRdoEheAHqsRmr2WuKZ
This commit is contained in:
5 files changed
+91
-15
No files matched your search
+10
-5
@@ -12,7 +12,8 @@ import { provePseudo, studyOf, defaultCall } from '../services/pseudo.js';
|
||||
import { mojoReadsInput, type MojoProgram } from '../services/mojo.js';
|
||||
import { runMojo } from '../mojo/interp.js';
|
||||
import { fuzzPseudo, fuzzMojo, type FuzzReport, type FuzzOptions } from './fuzz.js';
|
||||
import { compileMojo, compilerDiagnostics, listingFunctions, type BuildLevel, type CompileOutcome, type ListingFunction } from '../services/godbolt.js';
|
||||
import { compilerDiagnostics, listingFunctions, type BuildLevel, type CompileOptions, type CompileOutcome, type ListingFunction } from '../services/godbolt.js';
|
||||
import { compileBackend } from '../services/compile-backend.js';
|
||||
import { keepCompile, keptCompiles, compiledStatus, type CompiledStatus, type KeptCompile } from './compiles.js';
|
||||
import { mojoProvenance, type MojoProvenance } from './provenance.js';
|
||||
import { practicesOn } from './prefs.js';
|
||||
@@ -29,6 +30,8 @@ export interface CompileRecord {
|
||||
level: BuildLevel;
|
||||
at: number;
|
||||
outcome: CompileOutcome;
|
||||
/** The service that answered (compileBackend().host when asked); absent in records kept before it was stored, which all came from godbolt.org. */
|
||||
host?: string;
|
||||
/** The compiler's messages, on the Mojo pane's lines. */
|
||||
diagnostics: Diagnostic[];
|
||||
/** The listing, one entry per function. */
|
||||
@@ -319,16 +322,18 @@ export class Session {
|
||||
buildLevel(): BuildLevel { return this.state.build ?? 'O0'; }
|
||||
setBuildLevel(level: BuildLevel): void { this.state.build = level; this.persist(); this.emit('state'); }
|
||||
|
||||
/** Compile and run the Mojo pane on godbolt; the answer is kept for the views that read it. */
|
||||
compile(fetchImpl?: typeof compileMojo, levelOverride?: BuildLevel): Promise<CompileRecord | null> {
|
||||
/** Compile and run the Mojo pane on the compile backend (godbolt.org unless set otherwise); the answer is kept for the views that read it. */
|
||||
compile(fetchImpl?: (source: string, opts: CompileOptions) => Promise<CompileOutcome>, levelOverride?: BuildLevel): Promise<CompileRecord | null> {
|
||||
if (this.compiling) return this.compiling;
|
||||
const source = this.source('mojo');
|
||||
if (!source.trim()) return Promise.resolve(null);
|
||||
const stdin = this.inputLines().join('\n') + (this.inputLines().length ? '\n' : '');
|
||||
const level = levelOverride ?? this.buildLevel();
|
||||
this.compiling = (fetchImpl ?? compileMojo)(source, { stdin, level }).then((outcome) => {
|
||||
const backend = compileBackend();
|
||||
const ask = fetchImpl ?? ((src: string, opts: CompileOptions) => backend.compile(src, opts));
|
||||
this.compiling = ask(source, { stdin, level }).then((outcome) => {
|
||||
const rec: CompileRecord = {
|
||||
source, stdin, level, at: Date.now(), outcome,
|
||||
source, stdin, level, at: Date.now(), outcome, host: backend.host,
|
||||
diagnostics: outcome.answer ? compilerDiagnostics(outcome.answer.buildStderr) : [],
|
||||
functions: outcome.answer ? listingFunctions(outcome.answer.asm) : [],
|
||||
};
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
/**
|
||||
* Where Compile & run is sent. Every compile goes through one CompileBackend, so the app can move
|
||||
* off godbolt.org to a service of its own (a self-hosted Compiler Explorer, or the checker service
|
||||
* the proof stages plan, which will answer Mojo, Dafny and Lean) without touching the session or
|
||||
* the views. The default is godbolt.org with the pinned compiler (src/mojo/generated/pin.ts).
|
||||
*
|
||||
* A backend answers exactly what godbolt answers: the same request body (mojoRequestBody, which
|
||||
* tests/mojo.test.mjs holds to what the corpus pipeline sends) and the same answer shape
|
||||
* (normaliseAnswer), so a stored answer and a live one mean the same thing. Rule 3 in AGENTS.md
|
||||
* still holds whichever backend answers: the app never says a program compiles without one.
|
||||
*/
|
||||
import { compileMojo, GODBOLT_TARGET, type CompileOptions, type CompileOutcome, type CompileTarget } from './godbolt.js';
|
||||
|
||||
export interface CompileBackend {
|
||||
/** A short id, such as 'godbolt'. */
|
||||
id: string;
|
||||
/** The host a person sees in messages and tooltips, such as 'godbolt.org'. */
|
||||
host: string;
|
||||
/** The compiler id the service runs, such as 'mojo_1_1_0'. */
|
||||
compiler: string;
|
||||
compile(source: string, opts?: CompileOptions): Promise<CompileOutcome>;
|
||||
}
|
||||
|
||||
/** A backend that speaks Compiler Explorer's API at `target`. */
|
||||
export function explorerBackend(id: string, target: CompileTarget): CompileBackend {
|
||||
return { id, host: target.host, compiler: target.compiler, compile: (source, opts = {}) => compileMojo(source, opts, target) };
|
||||
}
|
||||
|
||||
export const GODBOLT: CompileBackend = explorerBackend('godbolt', GODBOLT_TARGET);
|
||||
|
||||
let current: CompileBackend = GODBOLT;
|
||||
|
||||
/** The backend Compile & run uses now. */
|
||||
export function compileBackend(): CompileBackend { return current; }
|
||||
|
||||
/** Send compiles somewhere else from now on (a self-hosted service, or a fake in a test). Returns the previous one. */
|
||||
export function setCompileBackend(b: CompileBackend): CompileBackend { const prev = current; current = b; return prev; }
|
||||
+13
-6
@@ -218,24 +218,31 @@ export function listingFunctions(asm: AsmLine[]): ListingFunction[] {
|
||||
|
||||
export interface CompileOutcome { answer: Answer | null; error: string | null; seconds: number }
|
||||
|
||||
/** Ask godbolt. A network or HTTP failure is an outcome to show, not an exception. */
|
||||
export async function compileMojo(source: string, opts: { stdin?: string; level?: BuildLevel; signal?: AbortSignal; timeoutMs?: number } = {}): Promise<CompileOutcome> {
|
||||
/** What a compile asks for, whichever service answers it. */
|
||||
export interface CompileOptions { stdin?: string; level?: BuildLevel; signal?: AbortSignal; timeoutMs?: number }
|
||||
/** Where a compile is sent: a service that speaks Compiler Explorer's API, at a base URL. */
|
||||
export interface CompileTarget { base: string; compiler: string; host: string }
|
||||
export const GODBOLT_TARGET: CompileTarget = { base: GODBOLT_BASE, compiler: GODBOLT_COMPILER, host: 'godbolt.org' };
|
||||
|
||||
/** Ask godbolt (or another Compiler Explorer). A network or HTTP failure is an outcome to show, not an exception. */
|
||||
export async function compileMojo(source: string, opts: CompileOptions = {}, target: CompileTarget = GODBOLT_TARGET): Promise<CompileOutcome> {
|
||||
const t0 = Date.now();
|
||||
const ctl = new AbortController();
|
||||
const timer = setTimeout(() => ctl.abort(), opts.timeoutMs ?? 60000);
|
||||
opts.signal?.addEventListener('abort', () => ctl.abort());
|
||||
const host = target.host;
|
||||
try {
|
||||
const res = await fetch(mojoRequestUrl(), {
|
||||
const res = await fetch(mojoRequestUrl(target.base, target.compiler), {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
|
||||
body: JSON.stringify(mojoRequestBody(source, opts.stdin ?? '', BUILD_ARGS[opts.level ?? 'O0'])),
|
||||
signal: ctl.signal,
|
||||
});
|
||||
if (res.status === 429) return { answer: null, error: 'godbolt.org is rate-limiting requests from here. Wait a minute and compile again.', seconds: (Date.now() - t0) / 1000 };
|
||||
if (!res.ok) return { answer: null, error: `godbolt.org answered ${res.status} ${res.statusText}.`, seconds: (Date.now() - t0) / 1000 };
|
||||
if (res.status === 429) return { answer: null, error: `${host} is rate-limiting requests from here. Wait a minute and compile again.`, seconds: (Date.now() - t0) / 1000 };
|
||||
if (!res.ok) return { answer: null, error: `${host} answered ${res.status} ${res.statusText}.`, seconds: (Date.now() - t0) / 1000 };
|
||||
return { answer: normaliseAnswer(await res.json()), error: null, seconds: (Date.now() - t0) / 1000 };
|
||||
} catch (e: any) {
|
||||
const msg = e?.name === 'AbortError' ? 'godbolt.org did not answer in time.' : `Could not reach godbolt.org (${e?.message || e}).`;
|
||||
const msg = e?.name === 'AbortError' ? `${host} did not answer in time.` : `Could not reach ${host} (${e?.message || e}).`;
|
||||
return { answer: null, error: msg, seconds: (Date.now() - t0) / 1000 };
|
||||
} finally {
|
||||
clearTimeout(timer);
|
||||
|
||||
@@ -15,7 +15,8 @@ import type { Session, CompileRecord } from '../../core/session.js';
|
||||
import type { AsmLine, BuildLevel, ListingFunction } from '../../services/godbolt.js';
|
||||
import { intelListing } from '../../mojo/att.js';
|
||||
import { tokenizeAsm } from '../../services/asm.js';
|
||||
import { MOJO_VERSION, GODBOLT_COMPILER } from '../../mojo/generated/pin.js';
|
||||
import { MOJO_VERSION } from '../../mojo/generated/pin.js';
|
||||
import { compileBackend } from '../../services/compile-backend.js';
|
||||
import type { PanelHooks } from './panels.js';
|
||||
import { generatedLabel } from '../provenance.js';
|
||||
|
||||
@@ -161,12 +162,12 @@ export function compilerView(session: Session, root: HTMLElement, hooks: Compile
|
||||
const kind = session.provenance();
|
||||
if (kind) add(head, generatedLabel(kind));
|
||||
if (session.compiling) {
|
||||
add(head, el('span', { class: 'badge badge-open' }, 'compiling'), el('span', { class: 'small muted' }, `Asking godbolt.org (${GODBOLT_COMPILER}) to build and run the Mojo pane…`));
|
||||
add(head, el('span', { class: 'badge badge-open' }, 'compiling'), el('span', { class: 'small muted' }, `Asking ${compileBackend().host} (${compileBackend().compiler}) to build and run the Mojo pane…`));
|
||||
if (!last) return;
|
||||
}
|
||||
if (!last) {
|
||||
add(head, el('span', { class: 'small muted' }, 'Not compiled yet.'), el('span', { class: 'spacer' }), button('Compile & run', () => hooks.compile(), { class: 'btn btn-small' }));
|
||||
add(root, el('p', { class: 'muted' }, `Compile & run (Ctrl+Enter) builds the Mojo pane with the real Mojo ${MOJO_VERSION} compiler on godbolt.org, runs it, and shows here what it printed, what the compiler said, and the instructions it produced. Programming+ ships no compiler of its own and never says a program compiles without asking one. The stepper beside the editor goes through it line by line in Programming+'s own interpreter, and says so when it meets something it does not model yet.`));
|
||||
add(root, el('p', { class: 'muted' }, `Compile & run (Ctrl+Enter) builds the Mojo pane with the real Mojo ${MOJO_VERSION} compiler on ${compileBackend().host}, runs it, and shows here what it printed, what the compiler said, and the instructions it produced. Programming+ ships no compiler of its own and never says a program compiles without asking one. The stepper beside the editor goes through it line by line in Programming+'s own interpreter, and says so when it meets something it does not model yet.`));
|
||||
return;
|
||||
}
|
||||
const { record: rec, fresh } = last;
|
||||
@@ -175,7 +176,7 @@ export function compilerView(session: Session, root: HTMLElement, hooks: Compile
|
||||
if (!session.compiling) {
|
||||
const badge = !a ? ['badge-broken', 'no answer'] : !a.compiled ? ['badge-broken', 'did not compile'] : a.timedOut ? ['badge-broken', 'timed out'] : !a.executed ? ['badge-open', 'compiled, did not run'] : a.exitCode === 0 ? ['badge-proved', 'ran, exit 0'] : ['badge-broken', `exited with ${a.exitCode}`];
|
||||
add(head, el('span', { class: `badge ${badge[0]}` }, badge[1]),
|
||||
el('span', { class: 'small muted' }, `Mojo ${MOJO_VERSION} on godbolt.org · ${rec.level === 'O0' ? 'as written (-O0)' : 'optimized'} · ${o.seconds.toFixed(1)} s`),
|
||||
el('span', { class: 'small muted' }, `Mojo ${MOJO_VERSION} on ${rec.host ?? 'godbolt.org'} · ${rec.level === 'O0' ? 'as written (-O0)' : 'optimized'} · ${o.seconds.toFixed(1)} s`),
|
||||
el('span', { class: 'spacer' }), button('Compile again', () => hooks.compile(), { class: 'btn btn-small btn-quiet' }));
|
||||
}
|
||||
if (!fresh) add(root, el('p', { class: 'hint' }, 'You have edited the Mojo pane since this answer; it is the answer for the earlier version. Compile again to see the current one.'));
|
||||
|
||||
@@ -213,6 +213,32 @@ test('the session keeps each answer with the source it answered, and says when i
|
||||
assert.equal(failed.outcome.error, 'Could not reach godbolt.org (offline).');
|
||||
});
|
||||
|
||||
test('Compile & run goes through the compile backend, and the record names the service that answered', async () => {
|
||||
const { compileBackend, setCompileBackend, explorerBackend, GODBOLT } = await import('../dist/services/compile-backend.js');
|
||||
assert.equal(compileBackend(), GODBOLT);
|
||||
assert.equal(GODBOLT.host, 'godbolt.org');
|
||||
assert.equal(GODBOLT.compiler, 'mojo_1_1_0');
|
||||
const asked = [];
|
||||
const fake = { id: 'fake', host: 'checker.example', compiler: 'mojo_1_1_0', compile: async (source, opts) => { asked.push({ source, ...opts }); return { answer: null, error: 'checker.example did not answer in time.', seconds: 0 }; } };
|
||||
const prev = setCompileBackend(fake);
|
||||
try {
|
||||
const s = new Session(normalize({ v: 3, lang: 'mojo', sources: { mojo: 'def main():\n print(7)\n' } }));
|
||||
const rec = await s.compile();
|
||||
assert.equal(asked.length, 1);
|
||||
assert.equal(asked[0].source, 'def main():\n print(7)\n');
|
||||
assert.equal(asked[0].level, 'O0');
|
||||
assert.equal(rec.host, 'checker.example');
|
||||
} finally {
|
||||
setCompileBackend(prev);
|
||||
}
|
||||
assert.equal(compileBackend(), GODBOLT);
|
||||
// a Compiler Explorer at another address speaks the same API and names itself in its messages
|
||||
const elsewhere = explorerBackend('local', { base: 'http://127.0.0.1:9', compiler: 'mojo_1_1_0', host: 'the local checker' });
|
||||
const out = await elsewhere.compile('def main():\n pass\n', { timeoutMs: 2000 });
|
||||
assert.equal(out.answer, null);
|
||||
assert.match(out.error, /the local checker/);
|
||||
});
|
||||
|
||||
test('godbolt\'s answer outlives the session: a new one for the same source finds it without asking again', async () => {
|
||||
const { forgetCompiles } = await import('../dist/core/compiles.js');
|
||||
forgetCompiles();
|
||||
|
||||
Reference in new issue
Block a user