laureen Claude Opus 5.5 commited on
Commit
20351b6
·
1 Parent(s): 2f61dfe

Underline C errors in the editor as the learner types

Browse files

A background Clang check marks errors in red and warnings in yellow,
with the compiler message shown on hover, in training and assessment.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

app/src/training/lint.worker.js ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Background syntax check for the editor's squiggles. It is separate from the
2
+ // compiler session so checking never waits for, or interrupts, a running program.
3
+ let compiler, running = false, pending = null;
4
+
5
+ async function check({ id, source, baseUrl }) {
6
+ compiler ??= await import(/* @vite-ignore */ new URL('training-compiler/bundle.js', baseUrl).href);
7
+ let diagnostics = '';
8
+ const decoder = new TextDecoder();
9
+ const collect = bytes => { if (bytes) diagnostics += decoder.decode(bytes, { stream: true }); };
10
+ try {
11
+ await compiler.runClang(['clang', '-fsyntax-only', '-std=c17', '-Wall', '-fno-color-diagnostics', '-fno-caret-diagnostics', '-ferror-limit=50', 'main.c'],
12
+ { 'main.c': source }, { stdout: collect, stderr: collect, decodeASCII: false });
13
+ } catch (error) {
14
+ if (!(error instanceof compiler.Exit)) throw error;
15
+ }
16
+ self.postMessage({ id, diagnostics: diagnostics + decoder.decode() });
17
+ }
18
+
19
+ self.onmessage = async ({ data }) => {
20
+ pending = data;
21
+ if (running) return;
22
+ running = true;
23
+ try {
24
+ while (pending) { const next = pending; pending = null; await check(next); }
25
+ } catch (error) {
26
+ self.postMessage({ error: error.message });
27
+ } finally { running = false; }
28
+ };
app/src/training/liveDiagnostics.js ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ const DIAGNOSTIC = /^main\.c:(\d+):(\d+): (fatal error|error|warning): (.*)$/gm;
2
+ const escape = value => value.replaceAll('&', '&amp;').replaceAll('<', '&lt;').replaceAll('>', '&gt;');
3
+ const encoder = new TextEncoder();
4
+
5
+ // Clang columns count UTF-8 bytes; the editor counts UTF-16 code units.
6
+ function byteColumnToIndex(line, column) {
7
+ let bytes = 0, index = 0;
8
+ for (const char of line) {
9
+ if (bytes >= column - 1) break;
10
+ bytes += encoder.encode(char).length;
11
+ index += char.length;
12
+ }
13
+ return index;
14
+ }
15
+
16
+ export function parseClangDiagnostics(text) {
17
+ return [...text.matchAll(DIAGNOSTIC)].map(([, line, column, severity, message]) => ({
18
+ line: Number(line), column: Number(column), severity: severity === 'warning' ? 'warning' : 'error', message,
19
+ }));
20
+ }
21
+
22
+ // Resolves line/column diagnostics against the current source, so marks stay
23
+ // on their line while the learner keeps typing before the next check.
24
+ export function diagnosticRanges(source, diagnostics) {
25
+ const lines = source.split('\n'), offsets = [];
26
+ for (let i = 0, offset = 0; i < lines.length; offset += lines[i].length + 1, i++) offsets.push(offset);
27
+ const ranges = [];
28
+ for (const diagnostic of diagnostics) {
29
+ const text = lines[diagnostic.line - 1];
30
+ if (text === undefined) continue;
31
+ let start = byteColumnToIndex(text, diagnostic.column), end;
32
+ const word = /^[A-Za-z_]\w*/.exec(text.slice(start));
33
+ if (word) end = start + word[0].length;
34
+ else if (start < text.length && /\S/.test(text[start])) end = start + 1;
35
+ else {
36
+ // "expected ';'" points just past the previous token: underline that token's last character.
37
+ const before = text.slice(0, start).trimEnd();
38
+ if (!before) continue;
39
+ start = before.length - 1; end = before.length;
40
+ }
41
+ ranges.push({ ...diagnostic, start: offsets[diagnostic.line - 1] + start, end: offsets[diagnostic.line - 1] + end });
42
+ }
43
+ ranges.sort((a, b) => a.start - b.start || (a.severity === 'error' ? -1 : 1));
44
+ // Marks cannot nest in the overlay: on overlap, an error wins over a warning.
45
+ const kept = [];
46
+ for (const range of ranges) {
47
+ const previous = kept.at(-1);
48
+ if (!previous || range.start >= previous.end) kept.push(range);
49
+ else if (range.severity === 'error' && previous.severity === 'warning') kept[kept.length - 1] = range;
50
+ }
51
+ return kept;
52
+ }
53
+
54
+ // Same text as the highlighter, drawn transparent, so only the wavy underlines show.
55
+ export function squiggleHtml(source, ranges) {
56
+ let html = '', last = 0;
57
+ ranges.forEach((range, index) => {
58
+ html += escape(source.slice(last, range.start));
59
+ html += `<span class="squiggle-${range.severity}" data-diagnostic="${index}">${escape(source.slice(range.start, range.end))}</span>`;
60
+ last = range.end;
61
+ });
62
+ return html + escape(source.slice(last)) + '\n';
63
+ }
app/src/ui/CodeTraining.jsx CHANGED
@@ -8,6 +8,7 @@ import { syntaxHintAtNewline, syntaxHintWhileEditing } from "../training/syntaxH
8
  import { SPEECH_LANGUAGES } from "../game/reachy/voiceProfile.js";
9
  import { askReachyLocally, webGpuAvailable } from "../training/reachyHelp.js";
10
  import { highlightC } from "../training/cSyntaxHighlight.js";
 
11
  import { EDITOR_FONTS, newlineEdit, wordRange, reindentC, tabEdit } from '../training/editorCommands.js';
12
  import { createRaceProtocol } from "../training/raceProtocol.js";
13
  import { createInteractionProtocol } from "../training/interactionProtocol.js";
@@ -100,7 +101,10 @@ export default function CodeTraining({ onClose }) {
100
  const provider = useGame((s) => s.speechProvider);
101
  const voice = useGame((s) => s.speech);
102
  const supported = !!WebAssembly.Suspending && !!WebAssembly.promising;
103
- const dialog = useRef(null), output = useRef(null), inputField = useRef(null), gutter = useRef(null), highlighter = useRef(null), fileInput = useRef(null);
 
 
 
104
  const session = useRef(null);
105
  const exam = useExam({ source, language, replaceSource: value => {
106
  stop(); setSource(value); setExercise(null); setExerciseOpen(false); setCompact(false);
@@ -151,6 +155,22 @@ export default function CodeTraining({ onClose }) {
151
  try { localStorage.setItem('training-editor-font', editorFont); localStorage.setItem('training-editor-size', String(editorSize)); } catch { /* optional preference storage */ }
152
  }, [editorFont, editorSize]);
153
  const highlighted = useMemo(() => highlightC(source, selectedWord), [source, selectedWord]);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
154
  useEffect(() => { if (!exam.active) try { localStorage.setItem(STORAGE, source); } catch { /* storage may be disabled */ } }, [source, exam.active]);
155
  useEffect(() => {
156
  for (const field of [output.current, exerciseOutput.current]) if (field) field.scrollTop = field.scrollHeight;
@@ -255,7 +275,7 @@ export default function CodeTraining({ onClose }) {
255
  const height = parseFloat(getComputedStyle(field).lineHeight);
256
  const top = (data.line - 1) * height;
257
  if (top < field.scrollTop || top > field.scrollTop + field.clientHeight - height * 2) field.scrollTop = Math.max(0, top - field.clientHeight / 3);
258
- gutter.current.scrollTop = highlighter.current.scrollTop = field.scrollTop; setEditorScroll(field.scrollTop);
259
  });
260
  } else if (data.type === "analyzed") {
261
  setDiagnostics(data.diagnostics);
@@ -421,6 +441,21 @@ export default function CodeTraining({ onClose }) {
421
  setInput(""); setPhase("running"); setStatus("Running — Reachy reads stdout."); arm(current);
422
  }
423
  function chooseSourceFile() { fileInput.current?.click(); }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
424
  function selectEditorWord(field = sourceField.current) {
425
  if (!field) return;
426
  const word = field.value.slice(field.selectionStart, field.selectionEnd);
@@ -434,7 +469,7 @@ export default function CodeTraining({ onClose }) {
434
  requestAnimationFrame(() => {
435
  field.setSelectionRange(edit.selectionStart ?? edit.caret, edit.caret);
436
  if (gutter.current) gutter.current.scrollTop = field.scrollTop;
437
- if (highlighter.current) { highlighter.current.scrollTop = field.scrollTop; highlighter.current.scrollLeft = field.scrollLeft; }
438
  });
439
  }
440
  async function loadPendingFile() {
@@ -506,9 +541,11 @@ export default function CodeTraining({ onClose }) {
506
  <div className="code-source">
507
  <div ref={gutter} className="debug-gutter" aria-label="Breakpoints">{source.split('\n').map((_, i) => <button key={i} type="button" className={`${breakpoints.includes(i + 1) ? 'has-breakpoint ' : ''}${debugPoint?.line === i + 1 ? 'current-line ' : ''}${debugLines.includes(i + 1) ? 'executable-line' : ''}`} aria-label={`Breakpoint line ${i + 1}`} aria-pressed={breakpoints.includes(i + 1)} title={`${exam.t('Point d’arrêt', 'Breakpoint')} ${i + 1}${debugLines.length && !debugLines.includes(i + 1) ? exam.t(' — pas d’instruction exécutable', ' — no executable statement') : ''}`} onClick={() => toggleBreakpoint(i + 1)}><span>{debugPoint?.line === i + 1 ? '➜' : breakpoints.includes(i + 1) ? '●' : '·'}</span>{i + 1}</button>)}</div>
508
  <div className="code-editor"><pre ref={highlighter} className="code-highlight" aria-hidden="true" dangerouslySetInnerHTML={{ __html: highlighted }} />
 
509
  {debugPoint && <div className="debug-line-highlight" aria-hidden="true" style={{ top: 12 + (debugPoint.line - 1) * editorSize * 1.5 - editorScroll, height: editorSize * 1.5 }} />}
510
  <textarea ref={sourceField} aria-label="C source code" autoFocus spellCheck="false" autoCapitalize="off" autoCorrect="off" value={source} readOnly={editorLocked}
511
- onScroll={(e) => { gutter.current.scrollTop = e.currentTarget.scrollTop; highlighter.current.scrollTop = e.currentTarget.scrollTop; highlighter.current.scrollLeft = e.currentTarget.scrollLeft; setEditorScroll(e.currentTarget.scrollTop); }}
 
512
  onChange={(e) => { setSource(e.target.value); if (e.nativeEvent.inputType !== "insertLineBreak") setSyntaxHint(null); }} onKeyDown={(e) => {
513
  if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === 'f' && !editorLocked) {
514
  e.preventDefault();
@@ -532,6 +569,7 @@ export default function CodeTraining({ onClose }) {
532
  const field = e.currentTarget, range = wordRange(field.value, field.selectionStart);
533
  if (range) { field.setSelectionRange(range.start, range.end); selectEditorWord(field); }
534
  }} />
 
535
  </div>
536
  </div>
537
  {syntaxHint && <p className="code-notice" aria-label="Syntax hint">Line {syntaxHint.line}: {syntaxHint.message}</p>}
 
8
  import { SPEECH_LANGUAGES } from "../game/reachy/voiceProfile.js";
9
  import { askReachyLocally, webGpuAvailable } from "../training/reachyHelp.js";
10
  import { highlightC } from "../training/cSyntaxHighlight.js";
11
+ import { diagnosticRanges, parseClangDiagnostics, squiggleHtml } from "../training/liveDiagnostics.js";
12
  import { EDITOR_FONTS, newlineEdit, wordRange, reindentC, tabEdit } from '../training/editorCommands.js';
13
  import { createRaceProtocol } from "../training/raceProtocol.js";
14
  import { createInteractionProtocol } from "../training/interactionProtocol.js";
 
101
  const provider = useGame((s) => s.speechProvider);
102
  const voice = useGame((s) => s.speech);
103
  const supported = !!WebAssembly.Suspending && !!WebAssembly.promising;
104
+ const dialog = useRef(null), output = useRef(null), inputField = useRef(null), gutter = useRef(null), highlighter = useRef(null), squiggles = useRef(null), fileInput = useRef(null);
105
+ const lintWorker = useRef(null);
106
+ const [lintDiagnostics, setLintDiagnostics] = useState([]);
107
+ const [hoveredDiagnostic, setHoveredDiagnostic] = useState(null);
108
  const session = useRef(null);
109
  const exam = useExam({ source, language, replaceSource: value => {
110
  stop(); setSource(value); setExercise(null); setExerciseOpen(false); setCompact(false);
 
155
  try { localStorage.setItem('training-editor-font', editorFont); localStorage.setItem('training-editor-size', String(editorSize)); } catch { /* optional preference storage */ }
156
  }, [editorFont, editorSize]);
157
  const highlighted = useMemo(() => highlightC(source, selectedWord), [source, selectedWord]);
158
+ const lintRanges = useMemo(() => diagnosticRanges(source, lintDiagnostics), [source, lintDiagnostics]);
159
+ const squiggled = useMemo(() => squiggleHtml(source, lintRanges), [source, lintRanges]);
160
+ // Like an IDE, re-check the source with Clang shortly after typing stops.
161
+ useEffect(() => {
162
+ if (!supported || !source.trim()) { setLintDiagnostics([]); return; }
163
+ const timer = setTimeout(() => {
164
+ if (!lintWorker.current) {
165
+ lintWorker.current = new Worker(new URL("../training/lint.worker.js", import.meta.url), { type: "module" });
166
+ lintWorker.current.onmessage = ({ data }) => { if (!data.error) setLintDiagnostics(parseClangDiagnostics(data.diagnostics)); };
167
+ }
168
+ lintWorker.current.postMessage({ source, baseUrl: new URL(import.meta.env.BASE_URL, location.href).href });
169
+ }, 600);
170
+ return () => clearTimeout(timer);
171
+ }, [source, supported]);
172
+ useEffect(() => () => lintWorker.current?.terminate(), []);
173
+ useEffect(() => setHoveredDiagnostic(null), [lintRanges]);
174
  useEffect(() => { if (!exam.active) try { localStorage.setItem(STORAGE, source); } catch { /* storage may be disabled */ } }, [source, exam.active]);
175
  useEffect(() => {
176
  for (const field of [output.current, exerciseOutput.current]) if (field) field.scrollTop = field.scrollHeight;
 
275
  const height = parseFloat(getComputedStyle(field).lineHeight);
276
  const top = (data.line - 1) * height;
277
  if (top < field.scrollTop || top > field.scrollTop + field.clientHeight - height * 2) field.scrollTop = Math.max(0, top - field.clientHeight / 3);
278
+ gutter.current.scrollTop = highlighter.current.scrollTop = squiggles.current.scrollTop = field.scrollTop; setEditorScroll(field.scrollTop);
279
  });
280
  } else if (data.type === "analyzed") {
281
  setDiagnostics(data.diagnostics);
 
441
  setInput(""); setPhase("running"); setStatus("Running — Reachy reads stdout."); arm(current);
442
  }
443
  function chooseSourceFile() { fileInput.current?.click(); }
444
+ // The textarea covers the squiggle layer, so hit-test its marks by position.
445
+ function hoverSquiggle(x, y) {
446
+ const layer = squiggles.current;
447
+ if (!layer) return;
448
+ const editor = layer.getBoundingClientRect();
449
+ for (const mark of layer.querySelectorAll('[data-diagnostic]')) {
450
+ const box = [...mark.getClientRects()].find(rect => x >= rect.left && x <= rect.right && y >= rect.top && y <= rect.bottom + 4);
451
+ if (!box) continue;
452
+ const range = lintRanges[mark.dataset.diagnostic];
453
+ const below = box.bottom - editor.top + 4;
454
+ if (hoveredDiagnostic?.range !== range) setHoveredDiagnostic({ range, severity: range.severity, message: range.message, left: Math.max(0, box.left - editor.left), top: below + 60 > editor.height ? box.top - editor.top - 4 : below, above: below + 60 > editor.height });
455
+ return;
456
+ }
457
+ if (hoveredDiagnostic) setHoveredDiagnostic(null);
458
+ }
459
  function selectEditorWord(field = sourceField.current) {
460
  if (!field) return;
461
  const word = field.value.slice(field.selectionStart, field.selectionEnd);
 
469
  requestAnimationFrame(() => {
470
  field.setSelectionRange(edit.selectionStart ?? edit.caret, edit.caret);
471
  if (gutter.current) gutter.current.scrollTop = field.scrollTop;
472
+ for (const layer of [highlighter.current, squiggles.current]) if (layer) { layer.scrollTop = field.scrollTop; layer.scrollLeft = field.scrollLeft; }
473
  });
474
  }
475
  async function loadPendingFile() {
 
541
  <div className="code-source">
542
  <div ref={gutter} className="debug-gutter" aria-label="Breakpoints">{source.split('\n').map((_, i) => <button key={i} type="button" className={`${breakpoints.includes(i + 1) ? 'has-breakpoint ' : ''}${debugPoint?.line === i + 1 ? 'current-line ' : ''}${debugLines.includes(i + 1) ? 'executable-line' : ''}`} aria-label={`Breakpoint line ${i + 1}`} aria-pressed={breakpoints.includes(i + 1)} title={`${exam.t('Point d’arrêt', 'Breakpoint')} ${i + 1}${debugLines.length && !debugLines.includes(i + 1) ? exam.t(' — pas d’instruction exécutable', ' — no executable statement') : ''}`} onClick={() => toggleBreakpoint(i + 1)}><span>{debugPoint?.line === i + 1 ? '➜' : breakpoints.includes(i + 1) ? '●' : '·'}</span>{i + 1}</button>)}</div>
543
  <div className="code-editor"><pre ref={highlighter} className="code-highlight" aria-hidden="true" dangerouslySetInnerHTML={{ __html: highlighted }} />
544
+ <pre ref={squiggles} className="code-highlight code-squiggles" aria-hidden="true" dangerouslySetInnerHTML={{ __html: squiggled }} />
545
  {debugPoint && <div className="debug-line-highlight" aria-hidden="true" style={{ top: 12 + (debugPoint.line - 1) * editorSize * 1.5 - editorScroll, height: editorSize * 1.5 }} />}
546
  <textarea ref={sourceField} aria-label="C source code" autoFocus spellCheck="false" autoCapitalize="off" autoCorrect="off" value={source} readOnly={editorLocked}
547
+ onScroll={(e) => { gutter.current.scrollTop = e.currentTarget.scrollTop; for (const layer of [highlighter.current, squiggles.current]) { layer.scrollTop = e.currentTarget.scrollTop; layer.scrollLeft = e.currentTarget.scrollLeft; } setEditorScroll(e.currentTarget.scrollTop); setHoveredDiagnostic(null); }}
548
+ onMouseMove={(e) => hoverSquiggle(e.clientX, e.clientY)} onMouseLeave={() => setHoveredDiagnostic(null)}
549
  onChange={(e) => { setSource(e.target.value); if (e.nativeEvent.inputType !== "insertLineBreak") setSyntaxHint(null); }} onKeyDown={(e) => {
550
  if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === 'f' && !editorLocked) {
551
  e.preventDefault();
 
569
  const field = e.currentTarget, range = wordRange(field.value, field.selectionStart);
570
  if (range) { field.setSelectionRange(range.start, range.end); selectEditorWord(field); }
571
  }} />
572
+ {hoveredDiagnostic && <div className={`squiggle-tooltip is-${hoveredDiagnostic.severity}`} role="tooltip" style={{ left: hoveredDiagnostic.left, top: hoveredDiagnostic.top, transform: hoveredDiagnostic.above ? 'translateY(-100%)' : undefined }}>{hoveredDiagnostic.message}</div>}
573
  </div>
574
  </div>
575
  {syntaxHint && <p className="code-notice" aria-label="Syntax hint">Line {syntaxHint.line}: {syntaxHint.message}</p>}
app/src/ui/codeTraining.css CHANGED
@@ -79,6 +79,11 @@
79
  .code-editor { position: relative; flex: 1; min-width: 0; overflow: hidden; }
80
  .code-source .code-highlight { position: absolute; inset: 0; box-sizing: border-box; width: 100%; height: 100%; text-align: left; color: #d4d4d4; background: transparent; white-space: pre; pointer-events: none; }
81
  .code-source textarea { position: absolute; inset: 0; box-sizing: border-box; width: 100%; height: 100%; resize: none; background: transparent; color: transparent; caret-color: #f2eee7; white-space: pre; overflow: auto; }
 
 
 
 
 
82
  .code-source textarea::selection { background: rgba(73, 130, 190, .58); color: transparent; }
83
  .token-keyword, .token-type { color: #569cd6; }
84
  .token-control, .token-preprocessor { color: #c586c0; }
 
79
  .code-editor { position: relative; flex: 1; min-width: 0; overflow: hidden; }
80
  .code-source .code-highlight { position: absolute; inset: 0; box-sizing: border-box; width: 100%; height: 100%; text-align: left; color: #d4d4d4; background: transparent; white-space: pre; pointer-events: none; }
81
  .code-source textarea { position: absolute; inset: 0; box-sizing: border-box; width: 100%; height: 100%; resize: none; background: transparent; color: transparent; caret-color: #f2eee7; white-space: pre; overflow: auto; }
82
+ .code-source .code-squiggles { color: transparent; }
83
+ .squiggle-error, .squiggle-warning { text-decoration: underline wavy #f14c4c; text-decoration-skip-ink: none; text-underline-offset: 3px; }
84
+ .squiggle-warning { text-decoration-color: #cca700; }
85
+ .squiggle-tooltip { position: absolute; z-index: 2; max-width: min(520px, 90%); padding: 5px 8px; color: #e8e4ee; background: #252131; border: 1px solid #514a5c; border-left: 3px solid #f14c4c; border-radius: 3px; font: 12px/1.4 var(--editor-font, Consolas, monospace); white-space: pre-wrap; pointer-events: none; box-shadow: 0 4px 12px #0008; }
86
+ .squiggle-tooltip.is-warning { border-left-color: #cca700; }
87
  .code-source textarea::selection { background: rgba(73, 130, 190, .58); color: transparent; }
88
  .token-keyword, .token-type { color: #569cd6; }
89
  .token-control, .token-preprocessor { color: #c586c0; }
app/test/browser/live-diagnostics.spec.js ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { test, expect } from "@playwright/test";
2
+
3
+ test("typos and unknown variables get red squiggles with the Clang message on hover", async ({ page }) => {
4
+ test.setTimeout(180000);
5
+ await page.goto("/?boot=1");
6
+ await page.waitForFunction(() => window.__store?.getState().bootDone || window.__store?.getState().bootFailed);
7
+ await page.evaluate(() => window.__gameApi.startEntrance?.());
8
+ await page.waitForFunction(() => window.rl && !window.rl.inputLocked);
9
+ await page.getByRole("button", { name: "CODE TRAINING", exact: true }).click();
10
+ const editor = page.getByRole("textbox", { name: "C source code" });
11
+ await editor.fill('#include <stdio.h>\nint main(void) {\n itn total = 0;\n pritnf("%d", totl);\n retrun 0;\n}\n');
12
+ const marks = page.locator(".code-squiggles .squiggle-error");
13
+ await expect(marks).toHaveText(["itn", "pritnf", "totl", "retrun"], { timeout: 120000 });
14
+ await page.screenshot({ path: test.info().outputPath("squiggles.png") });
15
+ const box = await marks.nth(2).boundingBox();
16
+ await page.mouse.move(box.x + box.width / 2, box.y + box.height / 2);
17
+ await expect(page.getByRole("tooltip")).toContainText("undeclared identifier 'totl'");
18
+ await page.screenshot({ path: test.info().outputPath("tooltip.png") });
19
+ await editor.fill('int main(void) {\n return 0;\n}\n');
20
+ await expect(marks).toHaveCount(0, { timeout: 30000 });
21
+ });
app/test/live-diagnostics.test.js ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import test from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import { diagnosticRanges, parseClangDiagnostics, squiggleHtml } from "../src/training/liveDiagnostics.js";
4
+
5
+ const SOURCE = 'int main(void) {\n itn total = 0;\n retrun totl\n}\n';
6
+ const CLANG = `main.c:2:3: error: unknown type name 'itn'
7
+ main.c:3:3: error: use of undeclared identifier 'retrun'
8
+ main.c:3:9: warning: unused expression [-Wunused-value]
9
+ main.c:3:14: error: expected ';' after expression
10
+ /usr/include/stdio.h:4:1: note: declared here
11
+ 2 errors generated.`;
12
+
13
+ test("Clang diagnostics become underlined ranges in main.c only", () => {
14
+ const diagnostics = parseClangDiagnostics(CLANG);
15
+ assert.equal(diagnostics.length, 4);
16
+ const ranges = diagnosticRanges(SOURCE, diagnostics);
17
+ assert.deepEqual(ranges.map(range => [SOURCE.slice(range.start, range.end), range.severity]), [
18
+ ['itn', 'error'], ['retrun', 'error'], ['l', 'error'],
19
+ ]);
20
+ assert.equal(ranges[0].message, "unknown type name 'itn'");
21
+ });
22
+
23
+ test("Marks follow UTF-8 columns and keep the text intact", () => {
24
+ const source = 'char *s = "été"; foo;';
25
+ const [range] = diagnosticRanges(source, parseClangDiagnostics("main.c:1:20: error: use of undeclared identifier 'foo'"));
26
+ assert.equal(source.slice(range.start, range.end), 'foo');
27
+ const html = squiggleHtml('a < b', [{ start: 4, end: 5, severity: 'error' }]);
28
+ assert.equal(html, 'a &lt; <span class="squiggle-error" data-diagnostic="0">b</span>\n');
29
+ });
30
+
31
+ test("Diagnostics on lines that no longer exist are dropped", () => {
32
+ assert.deepEqual(diagnosticRanges('int x;', parseClangDiagnostics("main.c:9:1: error: gone")), []);
33
+ });