File size: 5,568 Bytes
022cb3a b09157d 022cb3a b09157d 022cb3a b09157d 022cb3a 16215cb 022cb3a b09157d 16215cb 022cb3a 16215cb b09157d 022cb3a 16215cb 022cb3a 16215cb 022cb3a b09157d 022cb3a 16215cb 022cb3a b09157d 022cb3a b09157d 022cb3a b09157d 022cb3a | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 | import { executeC } from "./runtime.js";
import { instrumentC } from './debugInstrumentation.js';
import { DebugController } from './debugRuntime.js';
let compiler;
let binary;
let busy = false;
let reply;
let debuggerState;
let inspectArray, paused = false, pauseId = 0;
const send = (type, values = {}) => self.postMessage({ type, ...values });
const request = (type, values) => new Promise((resolve) => { reply = resolve; send(type, values); });
self.onmessage = async ({ data }) => {
if (data.type === 'debug-inspect') {
try {
if (!paused || data.pauseId !== pauseId || !inspectArray) throw new Error('The program is no longer paused here.');
send('debug-inspected', { requestId: data.requestId, page: inspectArray(data.arrayId, data.start) });
} catch (error) { send('debug-inspected', { requestId: data.requestId, error: error.message }); }
return;
}
if (data.type === 'breakpoints') { if (debuggerState) debuggerState.breakpoints = new Set(data.lines); return; }
if (data.type === "reply") { const resolve = reply; reply = null; resolve?.(data.value); return; }
if (busy) return;
busy = true;
try {
if (data.type === "compile" || data.type === "analyze") {
const analyzing = data.type === "analyze";
const actionLabel = analyzing ? "Analyse du code…" : "Compiling C…";
if (!analyzing) binary = null;
send("status", { text: compiler ? actionLabel : "Loading C compiler (first use)…" });
const url = new URL("training-compiler/bundle.js", data.baseUrl).href;
compiler ??= await import(/* @vite-ignore */ url);
let diagnostics = "";
const decoder = new TextDecoder();
const collect = (bytes) => { if (bytes) diagnostics += decoder.decode(bytes, { stream: true }); };
let lastProgress = -1;
try {
let source = data.source, debugLines = [];
debuggerState = !analyzing && data.debug ? new DebugController(data.breakpoints) : null;
if (debuggerState) {
let astText = ''; const astDecoder = new TextDecoder();
await compiler.runClang(['clang', '-std=c17', '-fsyntax-only', '-Xclang', '-ast-dump=json', '-fno-color-diagnostics', 'main.c'], { 'main.c': source }, {
stdout: bytes => { if (bytes) astText += astDecoder.decode(bytes, { stream: true }); }, stderr: collect, decodeASCII: false,
});
const instrumented = instrumentC(source, JSON.parse(astText + astDecoder.decode()));
source = instrumented.source; debugLines = instrumented.lines;
}
const flags = analyzing
// This browser Clang build omits RunAnalysis. Its semantic checks
// still provide real diagnostics without linking or running the code.
? ["clang", "-fsyntax-only", "-std=c17", "-Wall", "-Wextra", "-Wconversion", "-Wshadow", "-Wformat=2", "-fno-color-diagnostics", "-ferror-limit=8", "main.c"]
: [
"clang", "-std=c17", "-O0", "-Wall", "-Wextra", "-fno-color-diagnostics",
"-ferror-limit=8", "-Wl,--max-memory=67108864", "main.c", "terminal.c", "-lm", "-o", "main.wasm",
];
const files = await compiler.runClang(flags, {
"main.c": source,
"terminal.c": '#include <stdio.h>\n__attribute__((constructor)) static void terminal_init(void) { setvbuf(stdout, NULL, _IONBF, 0); setvbuf(stderr, NULL, _IONBF, 0); }\n',
}, {
stdout: collect, stderr: collect, decodeASCII: false,
fetchProgress: ({ doneLength, totalLength }) => {
const percent = Math.floor(doneLength / totalLength * 100);
if (percent !== lastProgress) { lastProgress = percent; send("status", { text: percent < 100 ? `Loading C compiler… ${percent}%` : actionLabel }); }
},
});
diagnostics += decoder.decode();
if (analyzing) { send("analyzed", { diagnostics }); return; }
binary = files["main.wasm"];
if (!(binary instanceof Uint8Array)) throw new Error("The compiler produced no executable.");
send("compiled", { ok: true, diagnostics, debugLines });
} catch (error) {
if (!(error instanceof compiler.Exit)) throw error;
if (analyzing && !/main\.c:\d+:\d+:.*error:/.test(diagnostics)) throw new Error(`Analyse indisponible : ${diagnostics || error.message}`);
send(analyzing ? "analyzed" : "compiled", { ok: false, diagnostics: diagnostics + decoder.decode() || error.message });
}
} else if (data.type === "run") {
if (!binary) throw new Error("Compile your program before running it.");
if (debuggerState) debuggerState.resume('into', Infinity);
let ticks = 0;
const code = await executeC(binary, {
read: () => request("input"),
write: (fd, text) => request("output", { fd, text }),
inspect: reader => { inspectArray = reader; },
debug: debuggerState ? async (point, snapshot) => {
if (debuggerState.shouldPause(point)) {
paused = true;
const command = await request('debug-paused', { ...point, variables: snapshot(), pauseId: ++pauseId });
paused = false;
debuggerState.resume(command || 'continue', point.depth);
} else if (++ticks % 128 === 0) await new Promise(resolve => setTimeout(resolve, 0));
} : undefined,
});
await request("flush");
send("exited", { code });
}
} catch (error) { send("error", { text: error?.message || String(error) }); }
finally { busy = false; paused = false; inspectArray = null; }
};
|