Baseline: tree as shared

This commit is contained in:
alexm committed 2026-10-05 03:03:38 +00:00
commit 659c03bbf8
1471 files changed
+990535

No files matched your search

+102
View File
@@ -0,0 +1,102 @@
/**
* lingo: the controlled-English service. Wraps `readSteps` from the course's
* english.js. Today the engine lowers English to pseudocode *text* and
* re-parses it; this adapter exposes that as `lower(..., 'pseudo')` with the
* engine's own line map, and runs English programs through the pseudocode
* service so the trace is the same shape.
*/
import { readSteps, SENTENCE_FORMS } from '../engines/pseudo/english.js';
import type { Diagnostic, LanguageService, Lowered, Parsed, RunOptions, Trace } from '../core/types.js';
import { toDiagnostic, studyOf, runPseudo, defaultCall as pseudoDefaultCall } from './pseudo.js';
export type Reading = any;
export function readLingo(source: string): Parsed<Reading> {
const r = readSteps(source);
const diagnostics: Diagnostic[] = r.diags.map((d: any) => toDiagnostic(d, 'lingo'));
return { program: r, diagnostics, ok: !!r.ok };
}
export function lowerLingo(parsed: Parsed<Reading>, target: string): Lowered | null {
const r = parsed.program;
if (!r || !r.pseudo) return null;
const lowered: Lowered = {
target: 'pseudo',
source: r.pseudo,
// lineMap[i] describes pseudocode line i+1 and names the English line it came from
map: (r.lineMap || []).map((m: any, i: number) => ({ from: m?.line ?? 0, to: i + 1 })).filter((m: { from: number }) => m.from > 0),
notes: [],
};
if (target === 'pseudo') return lowered;
return null;
}
/** Run an English program: lower it, then run the pseudocode with the English line numbers mapped back. */
export function runLingo(parsed: Parsed<Reading>, options: RunOptions): Trace {
const low = lowerLingo(parsed, 'pseudo');
if (!low) throw new Error('The steps do not read yet; answer the questions in the problems panel first.');
const st = studyOf(low.source);
if (!st.ok) throw new Error('The pseudocode these steps became has an error: ' + (st.diagnostics.find((d) => d.severity === 'error')?.message || ''));
// The call in the toolbar usually names the pseudocode pane's routine; aim it at the English routine instead.
let call = options.call ?? null;
const subs: Map<string, any> = st.program.program.subs;
const main = parsed.program.main;
const m = call ? /^\s*([A-Za-z_]\w*)\s*\((.*)\)\s*$/s.exec(call) : null;
if (m && main && !subs.has(m[1].toUpperCase())) {
const sub = subs.get(String(main.pseudo).toUpperCase());
const argc = m[2].trim() ? m[2].split(/,(?![^\[\]{}()]*[\]})])/).length : 0;
call = sub && sub.params.length === argc ? `${sub.name}(${m[2]})` : null;
}
const tr = runPseudo(st, { ...options, call: call ?? pseudoDefaultCall(st.program) });
const toEnglish = new Map(low.map.map((m) => [m.to, m.from]));
const hits = new Map<number, number>();
for (const [line, n] of tr.hits) { const e = toEnglish.get(line); if (e) hits.set(e, (hits.get(e) || 0) + n); }
return {
...tr,
lang: 'lingo',
hits,
steps: tr.steps.map((s: any) => ({ ...s, pseudoLine: s.line, line: toEnglish.get(s.line) ?? s.line })),
error: tr.error ? { ...tr.error, line: tr.error.line != null ? toEnglish.get(tr.error.line) ?? tr.error.line : null } : null,
};
}
export function defaultCallLingo(parsed: Parsed<Reading>): string | null {
const low = lowerLingo(parsed, 'pseudo');
if (!low) return null;
const st = studyOf(low.source);
return st.ok ? pseudoDefaultCall(st.program) : null;
}
const STEP_WORDS = /^(to|start|let|set|make|add|append|put|insert|subtract|increase|decrease|multiply|double|halve|count|remove|sort|swap|show|print|check|if|otherwise|for|repeat|while|until|stop|skip|the answer|example)\b/i;
export function tokenizeLingo(line: string): Array<{ text: string; cls: string }> {
const out: Array<{ text: string; cls: string }> = [];
const re = /("(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)?')|(\b\d+(?:\.\d+)?\b)|(\b[A-Za-z][A-Za-z0-9_]*\b)|(\s+)|(.)/g;
let m: RegExpExecArray | null;
let first = true;
while ((m = re.exec(line))) {
const [text, s, n, w] = m;
let cls = '';
if (s) cls = 'tok-string';
else if (n) cls = 'tok-number';
else if (w) {
if (first && STEP_WORDS.test(line.trim())) cls = 'tok-keyword';
else if (/^[A-Z]/.test(w) || w.length === 1) cls = 'tok-name';
first = false;
}
out.push({ text, cls });
}
return out;
}
export const sentenceForms: Array<{ job: string; example: string }> = (SENTENCE_FORMS as any[]).map((f) => ({ job: f.job || f.label || '', example: f.example || f.text || String(f) }));
export const lingoService: LanguageService<Reading> = {
id: 'lingo',
name: 'lingo',
parse: readLingo,
run: runLingo,
lower: lowerLingo,
defaultCall: defaultCallLingo,
tokenize: tokenizeLingo,
};