commit
e092cb029c
252 files changed
+35037
No files matched your search
@@ -0,0 +1,353 @@
|
||||
// SPDX-FileCopyrightText: 2026 Scientific Computing Studio, LLC
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
/**
|
||||
* A small document for rendering the app's views outside a browser (`quarto render` runs them in Node).
|
||||
*
|
||||
* The views (src/ui/views/) build their output with `document.createElement` and friends; this is just enough of
|
||||
* the DOM for them to do that, and to serialize what they built as HTML. It is not a browser: nothing is laid
|
||||
* out (sizes are zero), events never fire, timers and animation frames are queued for `flushQueued()` to run.
|
||||
* Only `installDocument()` touches the globals, and only when there is no real `document`.
|
||||
*
|
||||
* Selectors: what the views use and no more — a comma list of compound selectors (`tag`, `.class`, `#id`,
|
||||
* `[attr]`, `[attr="v"]`, `[attr^="v"]`), joined by the descendant combinator only.
|
||||
*/
|
||||
|
||||
const SVG_NS = 'http://www.w3.org/2000/svg';
|
||||
const VOID = new Set(['area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input', 'link', 'meta', 'source', 'track', 'wbr']);
|
||||
const RAW_TEXT = new Set(['style', 'script']);
|
||||
|
||||
export const escapeText = (s: string): string => s.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
|
||||
export const escapeAttr = (s: string): string => escapeText(s).replace(/"/g, '"');
|
||||
|
||||
/** `fontSize` → `font-size`; custom properties stay as they are. */
|
||||
const kebab = (k: string): string => (k.startsWith('--') ? k : k.replace(/[A-Z]/g, (c) => '-' + c.toLowerCase()));
|
||||
|
||||
export class SNode {
|
||||
parentNode: SElement | SFragment | null = null;
|
||||
readonly childNodes: SNode[] = [];
|
||||
nodeType = 0;
|
||||
get parentElement(): SElement | null { return this.parentNode instanceof SElement ? this.parentNode : null; }
|
||||
get firstChild(): SNode | null { return this.childNodes[0] ?? null; }
|
||||
get lastChild(): SNode | null { return this.childNodes[this.childNodes.length - 1] ?? null; }
|
||||
get nextSibling(): SNode | null { const p = this.parentNode; if (!p) return null; return p.childNodes[p.childNodes.indexOf(this) + 1] ?? null; }
|
||||
get previousSibling(): SNode | null { const p = this.parentNode; if (!p) return null; return p.childNodes[p.childNodes.indexOf(this) - 1] ?? null; }
|
||||
get textContent(): string { return this.childNodes.map((c) => c.textContent).join(''); }
|
||||
set textContent(v: string) { for (const c of this.childNodes) c.parentNode = null; this.childNodes.length = 0; if (v !== '' && v != null) this.appendChild(new SText(String(v))); }
|
||||
|
||||
appendChild<T extends SNode>(c: T): T { return this.insertBefore(c, null); }
|
||||
insertBefore<T extends SNode>(c: T, ref: SNode | null): T {
|
||||
if (c instanceof SFragment) { for (const k of [...c.childNodes]) this.insertBefore(k, ref); return c; }
|
||||
c.remove();
|
||||
const at = ref ? this.childNodes.indexOf(ref) : -1;
|
||||
if (at < 0) this.childNodes.push(c); else this.childNodes.splice(at, 0, c);
|
||||
c.parentNode = this as any;
|
||||
return c;
|
||||
}
|
||||
removeChild<T extends SNode>(c: T): T { const i = this.childNodes.indexOf(c); if (i >= 0) { this.childNodes.splice(i, 1); c.parentNode = null; } return c; }
|
||||
replaceChild(n: SNode, old: SNode): SNode { this.insertBefore(n, old); return this.removeChild(old); }
|
||||
remove(): void { this.parentNode?.removeChild(this); }
|
||||
append(...xs: Array<SNode | string>): void { for (const x of xs) this.appendChild(typeof x === 'string' ? new SText(x) : x); }
|
||||
prepend(...xs: Array<SNode | string>): void { const first = this.firstChild; for (const x of xs) this.insertBefore(typeof x === 'string' ? new SText(x) : x, first); }
|
||||
replaceChildren(...xs: Array<SNode | string>): void { this.textContent = ''; this.append(...xs); }
|
||||
before(...xs: Array<SNode | string>): void { const p = this.parentNode; if (p) for (const x of xs) p.insertBefore(typeof x === 'string' ? new SText(x) : x, this); }
|
||||
after(...xs: Array<SNode | string>): void { const p = this.parentNode; if (!p) return; const next = this.nextSibling; for (const x of xs) p.insertBefore(typeof x === 'string' ? new SText(x) : x, next); }
|
||||
replaceWith(...xs: Array<SNode | string>): void { this.before(...xs); this.remove(); }
|
||||
contains(n: SNode | null): boolean { for (let x: SNode | null = n; x; x = x.parentNode) if (x === this) return true; return false; }
|
||||
hasChildNodes(): boolean { return this.childNodes.length > 0; }
|
||||
cloneNode(deep = false): SNode { return this; }
|
||||
addEventListener(): void { /* nothing fires here */ }
|
||||
removeEventListener(): void { /* nothing fires here */ }
|
||||
dispatchEvent(): boolean { return true; }
|
||||
serialize(): string { return this.childNodes.map((c) => c.serialize()).join(''); }
|
||||
}
|
||||
|
||||
export class SText extends SNode {
|
||||
constructor(public data: string) { super(); this.nodeType = 3; }
|
||||
get textContent(): string { return this.data; }
|
||||
set textContent(v: string) { this.data = String(v); }
|
||||
get nodeValue(): string { return this.data; }
|
||||
cloneNode(): SText { return new SText(this.data); }
|
||||
serialize(): string { return this.parentNode instanceof SElement && RAW_TEXT.has(this.parentNode.localName) ? this.data : escapeText(this.data); }
|
||||
}
|
||||
|
||||
export class SComment extends SNode {
|
||||
constructor(public data: string) { super(); this.nodeType = 8; }
|
||||
get textContent(): string { return ''; }
|
||||
cloneNode(): SComment { return new SComment(this.data); }
|
||||
serialize(): string { return `<!--${this.data}-->`; }
|
||||
}
|
||||
|
||||
export class SFragment extends SNode {
|
||||
constructor() { super(); this.nodeType = 11; }
|
||||
get children(): SElement[] { return this.childNodes.filter((c): c is SElement => c instanceof SElement); }
|
||||
querySelector(sel: string): SElement | null { return this.querySelectorAll(sel)[0] ?? null; }
|
||||
querySelectorAll(sel: string): SElement[] { const m = compile(sel); const out: SElement[] = []; for (const c of this.children) c.collect(m, out, true); return out; }
|
||||
cloneNode(deep = false): SFragment { const f = new SFragment(); if (deep) for (const c of this.childNodes) f.appendChild(c.cloneNode(true)); return f; }
|
||||
}
|
||||
|
||||
class ClassList {
|
||||
constructor(private readonly owner: SElement) { }
|
||||
private get list(): string[] { return (this.owner.getAttribute('class') ?? '').split(/\s+/).filter(Boolean); }
|
||||
private set list(v: string[]) { this.owner.setAttribute('class', v.join(' ')); }
|
||||
get length(): number { return this.list.length; }
|
||||
contains(c: string): boolean { return this.list.includes(c); }
|
||||
add(...cs: string[]): void { const l = this.list; for (const c of cs) if (!l.includes(c)) l.push(c); this.list = l; }
|
||||
remove(...cs: string[]): void { this.list = this.list.filter((c) => !cs.includes(c)); }
|
||||
toggle(c: string, force?: boolean): boolean { const on = force ?? !this.contains(c); if (on) this.add(c); else this.remove(c); return on; }
|
||||
replace(a: string, b: string): void { if (this.contains(a)) { this.remove(a); this.add(b); } }
|
||||
toString(): string { return this.list.join(' '); }
|
||||
[Symbol.iterator](): Iterator<string> { return this.list[Symbol.iterator](); }
|
||||
}
|
||||
|
||||
/** `el.style`: properties set by name (`left`, `fontSize`) or with setProperty, written back as the style attribute. */
|
||||
function styleOf(owner: SElement): any {
|
||||
const props = new Map<string, string>();
|
||||
const sync = () => { if (props.size) owner.attrs.set('style', [...props].map(([k, v]) => `${k}: ${v}`).join('; ')); else owner.attrs.delete('style'); };
|
||||
const api = {
|
||||
setProperty(k: string, v: string) { if (v == null || v === '') props.delete(kebab(k)); else props.set(kebab(k), String(v)); sync(); },
|
||||
removeProperty(k: string) { props.delete(kebab(k)); sync(); },
|
||||
getPropertyValue(k: string) { return props.get(kebab(k)) ?? ''; },
|
||||
get cssText() { return owner.attrs.get('style') ?? ''; },
|
||||
set cssText(v: string) { props.clear(); for (const part of String(v).split(';')) { const i = part.indexOf(':'); if (i > 0) props.set(part.slice(0, i).trim(), part.slice(i + 1).trim()); } sync(); },
|
||||
};
|
||||
return new Proxy(api, {
|
||||
get: (t, k) => (k in t ? (t as any)[k] : typeof k === 'string' ? props.get(kebab(k)) ?? '' : undefined),
|
||||
set: (t, k, v) => { if (k === 'cssText') t.cssText = v; else if (typeof k === 'string') t.setProperty(k, v); return true; },
|
||||
});
|
||||
}
|
||||
|
||||
function datasetOf(owner: SElement): any {
|
||||
const attr = (k: string) => 'data-' + k.replace(/[A-Z]/g, (c) => '-' + c.toLowerCase());
|
||||
return new Proxy({}, {
|
||||
get: (_t, k) => (typeof k === 'string' ? owner.getAttribute(attr(k)) ?? undefined : undefined),
|
||||
set: (_t, k, v) => { if (typeof k === 'string') owner.setAttribute(attr(k), String(v)); return true; },
|
||||
deleteProperty: (_t, k) => { if (typeof k === 'string') owner.removeAttribute(attr(k)); return true; },
|
||||
});
|
||||
}
|
||||
|
||||
/** Properties that reflect an attribute: a string, or a boolean (present or absent). */
|
||||
const STRING_PROPS: Record<string, string> = { id: 'id', title: 'title', href: 'href', src: 'src', type: 'type', name: 'name', placeholder: 'placeholder', rel: 'rel', target: 'target', htmlFor: 'for', role: 'role', lang: 'lang', min: 'min', max: 'max', step: 'step', download: 'download', alt: 'alt' };
|
||||
const BOOL_PROPS: Record<string, string> = { hidden: 'hidden', open: 'open', disabled: 'disabled', readOnly: 'readonly', multiple: 'multiple', required: 'required', spellcheck: 'spellcheck' };
|
||||
|
||||
export class SElement extends SNode {
|
||||
readonly attrs = new Map<string, string>();
|
||||
readonly localName: string;
|
||||
private _classList?: ClassList;
|
||||
private _style?: any;
|
||||
private _dataset?: any;
|
||||
/** Form state, which a browser keeps apart from the attributes; serialized as attributes. */
|
||||
private _value: string | null = null;
|
||||
private _checked: boolean | null = null;
|
||||
private _selected: boolean | null = null;
|
||||
scrollTop = 0; scrollLeft = 0;
|
||||
readonly offsetWidth = 0; readonly offsetHeight = 0; readonly clientWidth = 0; readonly clientHeight = 0; readonly scrollWidth = 0; readonly scrollHeight = 0;
|
||||
|
||||
constructor(name: string, readonly namespaceURI: string | null = null) {
|
||||
super();
|
||||
this.nodeType = 1;
|
||||
this.localName = namespaceURI === SVG_NS ? name : name.toLowerCase();
|
||||
// the reflected properties, defined per instance so that `k in node` is true for them (src/ui/dom.ts el() asks)
|
||||
for (const [prop, attr] of Object.entries(STRING_PROPS)) Object.defineProperty(this, prop, { configurable: true, enumerable: false, get: () => this.getAttribute(attr) ?? '', set: (v) => this.setAttribute(attr, String(v)) });
|
||||
for (const [prop, attr] of Object.entries(BOOL_PROPS)) Object.defineProperty(this, prop, { configurable: true, enumerable: false, get: () => this.hasAttribute(attr), set: (v) => this.toggleAttribute(attr, !!v) });
|
||||
}
|
||||
get tagName(): string { return this.namespaceURI === SVG_NS ? this.localName : this.localName.toUpperCase(); }
|
||||
get nodeName(): string { return this.tagName; }
|
||||
get children(): SElement[] { return this.childNodes.filter((c): c is SElement => c instanceof SElement); }
|
||||
get firstElementChild(): SElement | null { return this.children[0] ?? null; }
|
||||
get lastElementChild(): SElement | null { const c = this.children; return c[c.length - 1] ?? null; }
|
||||
get childElementCount(): number { return this.children.length; }
|
||||
get className(): string { return this.getAttribute('class') ?? ''; }
|
||||
set className(v: string) { this.setAttribute('class', String(v)); }
|
||||
get classList(): ClassList { return (this._classList ??= new ClassList(this)); }
|
||||
get style(): any { return (this._style ??= styleOf(this)); }
|
||||
set style(v: any) { this.style.cssText = String(v); }
|
||||
get dataset(): any { return (this._dataset ??= datasetOf(this)); }
|
||||
|
||||
get value(): string {
|
||||
if (this.localName === 'select') { const opts = this.options; const sel = opts.find((o) => o.selected) ?? opts[0]; return sel ? sel.value : ''; }
|
||||
if (this.localName === 'option') return this._value ?? this.getAttribute('value') ?? this.textContent;
|
||||
if (this.localName === 'textarea') return this._value ?? this.textContent;
|
||||
return this._value ?? this.getAttribute('value') ?? '';
|
||||
}
|
||||
set value(v: string) {
|
||||
if (this.localName === 'select') { for (const o of this.options) o.selected = o.value === String(v); return; }
|
||||
this._value = String(v);
|
||||
}
|
||||
get checked(): boolean { return this._checked ?? this.hasAttribute('checked'); }
|
||||
set checked(v: boolean) { this._checked = !!v; }
|
||||
get selected(): boolean { return this._selected ?? this.hasAttribute('selected'); }
|
||||
set selected(v: boolean) {
|
||||
if (v && this.parentElement?.localName === 'select') for (const o of this.parentElement.options) if (o !== this) o._selected = false;
|
||||
this._selected = !!v;
|
||||
}
|
||||
get options(): SElement[] { const out: SElement[] = []; this.collect(compile('option'), out, true); return out; }
|
||||
get selectedIndex(): number { return this.options.findIndex((o) => o.selected); }
|
||||
set selectedIndex(i: number) { this.options.forEach((o, k) => { o.selected = k === i; }); }
|
||||
|
||||
getAttribute(k: string): string | null { return this.attrs.has(k) ? this.attrs.get(k)! : null; }
|
||||
setAttribute(k: string, v: string): void { this.attrs.set(k, String(v)); }
|
||||
setAttributeNS(_ns: string | null, k: string, v: string): void { this.setAttribute(k, v); }
|
||||
removeAttribute(k: string): void { this.attrs.delete(k); }
|
||||
hasAttribute(k: string): boolean { return this.attrs.has(k); }
|
||||
toggleAttribute(k: string, force?: boolean): boolean { const on = force ?? !this.hasAttribute(k); if (on) this.attrs.set(k, ''); else this.attrs.delete(k); return on; }
|
||||
get attributes(): Array<{ name: string; value: string }> { return [...this.attrs].map(([name, value]) => ({ name, value })); }
|
||||
|
||||
get innerHTML(): string { return super.serialize(); }
|
||||
set innerHTML(v: string) {
|
||||
// the views never parse markup; text is the safe reading of anything they might set
|
||||
this.textContent = String(v).replace(/<[^>]*>/g, '');
|
||||
}
|
||||
get outerHTML(): string { return this.serialize(); }
|
||||
|
||||
matches(sel: string): boolean { return compile(sel)(this); }
|
||||
closest(sel: string): SElement | null { const m = compile(sel); for (let e: SElement | null = this; e; e = e.parentElement) if (m(e)) return e; return null; }
|
||||
querySelector(sel: string): SElement | null { return this.querySelectorAll(sel)[0] ?? null; }
|
||||
querySelectorAll(sel: string): SElement[] { const out: SElement[] = []; for (const c of this.children) c.collect(compile(sel), out, true); return out; }
|
||||
getElementsByTagName(name: string): SElement[] { return this.querySelectorAll(name); }
|
||||
getElementsByClassName(name: string): SElement[] { return this.querySelectorAll('.' + name.trim().split(/\s+/).join('.')); }
|
||||
collect(m: Matcher, out: SElement[], self: boolean): void { if (self && m(this)) out.push(this); for (const c of this.children) c.collect(m, out, true); }
|
||||
|
||||
cloneNode(deep = false): SElement {
|
||||
const c = new SElement(this.localName, this.namespaceURI);
|
||||
for (const [k, v] of this.attrs) c.attrs.set(k, v);
|
||||
c._value = this._value; c._checked = this._checked; c._selected = this._selected;
|
||||
if (deep) for (const k of this.childNodes) c.appendChild(k.cloneNode(true));
|
||||
return c;
|
||||
}
|
||||
getBoundingClientRect() { return { x: 0, y: 0, top: 0, left: 0, right: 0, bottom: 0, width: 0, height: 0, toJSON() { return this; } }; }
|
||||
getClientRects() { return []; }
|
||||
scrollIntoView(): void { /* no layout */ }
|
||||
scrollTo(): void { /* no layout */ }
|
||||
focus(): void { /* no focus */ }
|
||||
blur(): void { /* no focus */ }
|
||||
click(): void { /* nothing fires */ }
|
||||
select(): void { /* no selection */ }
|
||||
getContext(): null { return null; }
|
||||
|
||||
serialize(): string {
|
||||
const attrs = new Map(this.attrs);
|
||||
// form state as markup, so the page shows what the view chose
|
||||
if (this._value !== null && (this.localName === 'input' || this.localName === 'option')) attrs.set('value', this._value);
|
||||
if (this._checked !== null) { if (this._checked) attrs.set('checked', ''); else attrs.delete('checked'); }
|
||||
if (this._selected !== null) { if (this._selected) attrs.set('selected', ''); else attrs.delete('selected'); }
|
||||
let open = '<' + this.localName;
|
||||
for (const [k, v] of attrs) open += v === '' && (k in BOOL_ATTR) ? ` ${k}` : ` ${k}="${escapeAttr(v)}"`;
|
||||
if (this.namespaceURI !== SVG_NS && VOID.has(this.localName)) return open + '>';
|
||||
if (this.localName === 'textarea' && this._value !== null) return `${open}>${escapeText(this._value)}</textarea>`;
|
||||
if (this.namespaceURI === SVG_NS && !this.childNodes.length) return open + '/>';
|
||||
return `${open}>${super.serialize()}</${this.localName}>`;
|
||||
}
|
||||
}
|
||||
const BOOL_ATTR: Record<string, true> = { hidden: true, open: true, disabled: true, readonly: true, checked: true, selected: true, multiple: true, required: true };
|
||||
|
||||
/* ---------- selectors ---------- */
|
||||
|
||||
type Matcher = (e: SElement) => boolean;
|
||||
const compiled = new Map<string, Matcher>();
|
||||
|
||||
function compile(sel: string): Matcher {
|
||||
const hit = compiled.get(sel);
|
||||
if (hit) return hit;
|
||||
const alts = sel.split(',').map((s) => s.trim()).filter(Boolean).map(descendant);
|
||||
const m: Matcher = (e) => alts.some((a) => a(e));
|
||||
compiled.set(sel, m);
|
||||
return m;
|
||||
}
|
||||
|
||||
/** `a b c`: c, inside a b, inside an a. */
|
||||
function descendant(s: string): Matcher {
|
||||
if (/[>+~]/.test(s.replace(/\[[^\]]*\]/g, ''))) throw new Error(`the render document does not handle the selector "${s}" (only the descendant combinator)`);
|
||||
const parts = s.split(/\s+(?![^\[]*\])/).filter(Boolean).map(compound);
|
||||
const last = parts.pop()!;
|
||||
return (e) => {
|
||||
if (!last(e)) return false;
|
||||
let k = parts.length - 1;
|
||||
for (let a = e.parentElement; a && k >= 0; a = a.parentElement) if (parts[k](a)) k--;
|
||||
return k < 0;
|
||||
};
|
||||
}
|
||||
|
||||
function compound(s: string): Matcher {
|
||||
const tests: Matcher[] = [];
|
||||
const re = /^([a-zA-Z][\w-]*|\*)|\.([\w-]+)|#([\w-]+)|\[([\w-]+)(?:([\^$*]?=)"?([^"\]]*)"?)?\]/g;
|
||||
let m: RegExpExecArray | null;
|
||||
let pos = 0;
|
||||
while ((m = re.exec(s))) {
|
||||
if (m.index !== pos) break;
|
||||
pos = re.lastIndex;
|
||||
const [, tag, cls, id, attr, op, val] = m;
|
||||
if (tag && tag !== '*') tests.push((e) => e.localName.toLowerCase() === tag.toLowerCase());
|
||||
else if (cls) tests.push((e) => e.classList.contains(cls));
|
||||
else if (id) tests.push((e) => e.getAttribute('id') === id);
|
||||
else if (attr) tests.push((e) => {
|
||||
const v = e.getAttribute(attr);
|
||||
if (v === null) return false;
|
||||
if (!op) return true;
|
||||
return op === '=' ? v === val : op === '^=' ? v.startsWith(val) : op === '$=' ? v.endsWith(val) : v.includes(val);
|
||||
});
|
||||
}
|
||||
if (pos !== s.length) throw new Error(`the render document does not handle the selector "${s}"`);
|
||||
return (e) => tests.every((t) => t(e));
|
||||
}
|
||||
|
||||
/* ---------- the document, and the globals ---------- */
|
||||
|
||||
export class SDocument extends SFragment {
|
||||
readonly documentElement = new SElement('html');
|
||||
readonly head = new SElement('head');
|
||||
readonly body = new SElement('body');
|
||||
constructor() { super(); this.nodeType = 9; this.appendChild(this.documentElement); this.documentElement.append(this.head, this.body); }
|
||||
createElement(tag: string): SElement { return new SElement(tag); }
|
||||
createElementNS(ns: string | null, tag: string): SElement { return new SElement(tag, ns); }
|
||||
createTextNode(s: string): SText { return new SText(String(s)); }
|
||||
createComment(s: string): SComment { return new SComment(String(s)); }
|
||||
createDocumentFragment(): SFragment { return new SFragment(); }
|
||||
getElementById(id: string): SElement | null { return this.querySelector('#' + id); }
|
||||
execCommand(): boolean { return false; }
|
||||
get activeElement(): null { return null; }
|
||||
}
|
||||
|
||||
const queued: Array<() => void> = [];
|
||||
|
||||
/** Run what the views put off to the next frame or a timer (a view that measures before drawing), until none is left. */
|
||||
export function flushQueued(rounds = 8): void {
|
||||
for (let i = 0; i < rounds && queued.length; i++) for (const fn of queued.splice(0)) { try { fn(); } catch { /* a view's late refinement, not its output */ } }
|
||||
}
|
||||
|
||||
let installed: SDocument | null = null;
|
||||
|
||||
/**
|
||||
* Give this process a `document` (and the few other browser globals the views reach for). Does nothing where a
|
||||
* real document exists, so the same render code runs in the app's gallery and under `quarto render`.
|
||||
*/
|
||||
export function installDocument(): boolean {
|
||||
const g = globalThis as any;
|
||||
if (g.document && !installed) return false;
|
||||
if (installed) return true;
|
||||
installed = new SDocument();
|
||||
const store = new Map<string, string>();
|
||||
g.document = installed;
|
||||
g.Node = SNode; g.Element = SElement; g.HTMLElement = SElement; g.SVGElement = SElement; g.Text = SText; g.DocumentFragment = SFragment;
|
||||
g.localStorage ??= { getItem: (k: string) => store.get(k) ?? null, setItem: (k: string, v: string) => void store.set(k, String(v)), removeItem: (k: string) => void store.delete(k), clear: () => store.clear(), key: (i: number) => [...store.keys()][i] ?? null, get length() { return store.size; } };
|
||||
g.requestAnimationFrame ??= (fn: (t: number) => void) => { queued.push(() => fn(0)); return queued.length; };
|
||||
g.cancelAnimationFrame ??= () => { /* queued work runs at most once */ };
|
||||
g.ResizeObserver ??= class { observe() { /* no layout */ } unobserve() { /* no layout */ } disconnect() { /* no layout */ } };
|
||||
g.IntersectionObserver ??= class { observe() { /* no layout */ } unobserve() { /* no layout */ } disconnect() { /* no layout */ } };
|
||||
g.MutationObserver ??= class { observe() { /* nothing changes */ } disconnect() { /* nothing changes */ } takeRecords() { return []; } };
|
||||
g.getComputedStyle ??= () => ({ getPropertyValue: () => '' });
|
||||
g.matchMedia ??= () => ({ matches: false, addEventListener() { /* static */ }, removeEventListener() { /* static */ }, addListener() { /* static */ }, removeListener() { /* static */ } });
|
||||
// a window whose timers are queued with the animation frames: the render reads the views once, after flushQueued()
|
||||
g.window ??= g;
|
||||
if (g.window === g) {
|
||||
g.innerWidth ??= 1200; g.innerHeight ??= 800; g.devicePixelRatio ??= 1;
|
||||
g.addEventListener ??= () => { /* nothing fires */ }; g.removeEventListener ??= () => { /* nothing fires */ };
|
||||
g.location ??= { href: 'https://pplus.invalid/', hash: '', search: '', origin: 'https://pplus.invalid' };
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/** The HTML of what a view built: an element's children, as markup. */
|
||||
export function htmlOf(node: unknown): string {
|
||||
if (node instanceof SNode) return node.serialize();
|
||||
return (node as any).innerHTML as string;
|
||||
}
|
||||
@@ -0,0 +1,196 @@
|
||||
// SPDX-FileCopyrightText: 2026 Scientific Computing Studio, LLC
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
/**
|
||||
* The machine, rendered with the page: the Hardware area's board views (registers, memory, the stack, the caches,
|
||||
* virtual memory, the pipeline, the out-of-order core, the encoding...) over an x86-64 run, for the Quarto
|
||||
* extension's `pplus-hw` shortcodes.
|
||||
*
|
||||
* The views are the course's own (src/engines/asm86/views.js and hwviews.js), mounted exactly as the board mounts
|
||||
* them (`mountView`, `courseViews` in core/hardware.ts) and drawn at every step of the run. A page cannot run them,
|
||||
* so each card keeps what it drew at each step: the distinct drawings once, and which one each step shows. pplus.js
|
||||
* steps through them; render.mjs compresses them (they repeat from step to step, so deflate makes a run of a
|
||||
* hundred steps a few kilobytes per card). The step the page opens on is in the markup itself, so the page reads,
|
||||
* prints and works without script.
|
||||
*/
|
||||
import { el, add } from '../ui/dom.js';
|
||||
import type { Session } from '../core/session.js';
|
||||
import { BOARD_VIEWS, BOARD_PRESETS, boardFrame, boardView, courseViews, parseMachine, machineLabel, machineName, type BoardViewId } from '../core/hardware.js';
|
||||
import { mountView } from '../ui/hw/board.js';
|
||||
import { machineView } from '../ui/views/panels.js';
|
||||
import { highlighted, freeze } from './render.js';
|
||||
|
||||
/**
|
||||
* The machine's views as the shortcodes name them: `pplus-hw-<name>`. The name is the board's id, except where a
|
||||
* shortcode of that name already means something else (the ALU is `bits` on the board, the whole core `machine`).
|
||||
*/
|
||||
export const HW_NAMES: Record<string, BoardViewId> = {
|
||||
code: 'code', explain: 'explain', registers: 'registers', flags: 'flags', address: 'address', memory: 'memory', stack: 'stack',
|
||||
dataflow: 'dataflow', alu: 'bits', branches: 'branches', vectors: 'vectors',
|
||||
lines: 'lines', cache: 'cache', hierarchy: 'hierarchy', paging: 'paging',
|
||||
pipeline: 'pipeline', uops: 'uops', timeline: 'timeline', bottleneck: 'bottleneck', counters: 'counters',
|
||||
chip: 'machine', core: 'core', encoding: 'encoding',
|
||||
};
|
||||
|
||||
/** The board's arrangements a page can ask for (`preset=`), without the Mojo one (the machine cards only). */
|
||||
export const HW_PRESETS = BOARD_PRESETS.filter((p) => p.id !== 'mojo').map((p) => ({ id: p.id, label: p.label, blurb: p.blurb, views: p.items.map((x) => x.id).filter((id) => boardView(id)!.needs === 'asm') }));
|
||||
|
||||
/** A view by its shortcode name or its board id. */
|
||||
export function hwView(name: string): BoardViewId | null {
|
||||
const n = name.trim().toLowerCase();
|
||||
if (HW_NAMES[n]) return HW_NAMES[n];
|
||||
const v = boardView(n);
|
||||
return v && v.needs === 'asm' ? v.id : null;
|
||||
}
|
||||
|
||||
/** What pplus.js reads: for each card, its distinct drawings, and which one each step shows. */
|
||||
export interface HwData {
|
||||
count: number;
|
||||
t: number;
|
||||
/** Per step: the line of the instruction about to run (`n`) and of the one that just ran (`l`), and that instruction's text. */
|
||||
steps: Array<{ n: number | null; l: number | null; x: string }>;
|
||||
cards: Array<{ id: string; frames: string[]; at: number[] }>;
|
||||
/** Steps drawn: every one, or every `stride`-th when the run is longer than `max`. */
|
||||
shown: number[];
|
||||
}
|
||||
|
||||
export interface HwRequest { views?: string[]; preset?: string; t?: number; max?: number; listing?: boolean; stepper?: boolean }
|
||||
|
||||
export function machineBoard(session: Session, req: HwRequest): { node: HTMLElement; markdown: string; warnings: string[]; data: HwData | null } {
|
||||
const warnings: string[] = [];
|
||||
session.state.lang = 'asm';
|
||||
// the views asked for, in order; unknown ones are reported, and paging turns virtual memory on
|
||||
let ids: BoardViewId[] = [];
|
||||
if (req.views?.length) {
|
||||
for (const v of req.views) { const id = hwView(v); if (id) { if (!ids.includes(id)) ids.push(id); } else warnings.push(`hw: no machine view "${v}"; the views are ${Object.keys(HW_NAMES).join(', ')}`); }
|
||||
}
|
||||
if (!ids.length) ids = (HW_PRESETS.find((p) => p.id === req.preset) ?? HW_PRESETS[0]).views;
|
||||
if (req.preset && !req.views?.length && !HW_PRESETS.some((p) => p.id === req.preset)) warnings.push(`hw: no preset "${req.preset}"; the presets are ${HW_PRESETS.map((p) => p.id).join(', ')}`);
|
||||
if (ids.includes('paging') && !parseMachine(session.state.machine).paging) session.state.machine = machineName({ preset: parseMachine(session.state.machine).preset, paging: true });
|
||||
|
||||
const tr = session.trace();
|
||||
const trace = tr && tr.lang === 'asm' ? (tr.raw as any)?.trace : null;
|
||||
if (!session.source('asm').trim()) {
|
||||
const why = 'The machine views run an x86-64 file (asm=, with its setup=). For a Mojo program, `pixi run quarto-export` writes the compiler\'s x86-64 and setup beside the page.';
|
||||
return { node: el('div', {}, el('p', { class: 'pplus-err' }, why)), markdown: `*${why}*`, warnings: [...warnings, 'hw: no x86-64 file (asm=)'], data: null };
|
||||
}
|
||||
if (!trace) {
|
||||
const why = session.runError ?? session.diagnostics('asm').find((d) => d.severity === 'error')?.message ?? 'The x86-64 file does not assemble.';
|
||||
return { node: el('div', {}, el('p', { class: 'pplus-err' }, `It does not run: ${why}`)), markdown: `*It does not run: ${why}*`, warnings: [...warnings, `hw: ${why}`], data: null };
|
||||
}
|
||||
|
||||
const machine = parseMachine(session.state.machine);
|
||||
const count: number = trace.count;
|
||||
const max = Math.max(10, Math.min(req.max ?? 400, 5000));
|
||||
const stride = Math.max(1, Math.ceil(count / max));
|
||||
const shown: number[] = [];
|
||||
for (let t = 0; t <= count; t += stride) shown.push(t);
|
||||
if (shown[shown.length - 1] !== count) shown.push(count);
|
||||
const t0 = Math.max(0, Math.min(req.t ?? 0, count));
|
||||
// the step the page opens on is one of those drawn
|
||||
const open = shown.reduce((best, t) => (Math.abs(t - t0) < Math.abs(best - t0) ? t : best), shown[0]);
|
||||
const stepper = req.stepper !== false && count > 0;
|
||||
|
||||
const lineOf = (instr: any) => (instr && typeof instr.lineNo === 'number' ? instr.lineNo + 1 : null);
|
||||
const steps = shown.map((t) => { const f = boardFrame(trace, t); return { n: lineOf(f.next), l: lineOf(f.last?.instr), x: String(f.last?.instr?.text ?? '').trim().replace(/\s+/g, ' ') }; });
|
||||
|
||||
const cards: HwData['cards'] = [];
|
||||
const grid = el('div', { class: 'pplus-hw-grid' });
|
||||
// the listing stands beside the cards (sticky while they scroll), unless the machine-code card is one of them
|
||||
let listing: HTMLElement | null = null;
|
||||
if (req.listing !== false && !ids.includes('code')) {
|
||||
const code = highlighted(session.source('asm'), 'asm', { numbers: true });
|
||||
const at = steps[shown.indexOf(open)];
|
||||
for (const ln of [...code.querySelectorAll('.pplus-ln')]) {
|
||||
const n = Number(ln.getAttribute('data-line'));
|
||||
if (n === at.n) ln.classList.add('is-next');
|
||||
if (n === at.l) ln.classList.add('is-last');
|
||||
}
|
||||
listing = el('section', { class: 'pplus-hw-card pplus-hw-listing', 'data-hw': 'listing' }, el('div', { class: 'pplus-hw-title' }, 'x86-64'), code);
|
||||
}
|
||||
for (const id of ids) {
|
||||
const def = boardView(id)!;
|
||||
const card = el('section', { class: `pplus-hw-card pplus-hw-${id}${def.wide ? ' is-wide' : ''}`, 'data-hw': id, title: def.blurb });
|
||||
add(grid, card);
|
||||
if (id === 'counters') {
|
||||
// the run's totals: the same at every step
|
||||
const box = el('div', { class: 'view view-asm' });
|
||||
machineView(session, box);
|
||||
freeze(box);
|
||||
add(card, el('div', { class: 'pplus-hw-title' }, def.label), box);
|
||||
continue;
|
||||
}
|
||||
const spec = id === 'lines' ? { name: 'lines', options: {} } : courseViews([{ id }], trace, machine)[0];
|
||||
if (!spec) continue;
|
||||
const view = mountView(spec.name, trace, spec.options);
|
||||
const frames: string[] = [];
|
||||
const index = new Map<string, number>();
|
||||
const at: number[] = [];
|
||||
let first = '';
|
||||
for (const t of stepper ? shown : [open]) {
|
||||
view.update(boardFrame(trace, t));
|
||||
const html = inert(view.node.outerHTML);
|
||||
if (!index.has(html)) { index.set(html, frames.length); frames.push(html); }
|
||||
at.push(index.get(html)!);
|
||||
if (t === open) first = html;
|
||||
}
|
||||
if (view.node.classList.contains('has-failed')) warnings.push(`hw: the ${def.label} view failed on this run`);
|
||||
const holder = el('div', { class: 'a86 board-a86', 'data-hw-frame': '' });
|
||||
// the drawing for the step the page opens on: the course view's own markup. In a browser (the gallery) it goes
|
||||
// in directly; the small document has no parser, so there it is spliced into the serialized page (spliceFrames)
|
||||
if (typeof DOMParser !== 'undefined') holder.innerHTML = first;
|
||||
else (holder as any).__html = first;
|
||||
add(card, holder);
|
||||
cards.push({ id, frames, at });
|
||||
}
|
||||
|
||||
const data: HwData = { count, t: open, steps, cards, shown };
|
||||
const btn = (go: string, label: string, title: string) => el('button', { type: 'button', class: 'pplus-btn', 'data-go': go, title, 'aria-label': title }, label);
|
||||
const node = el('div', { 'data-count': String(count), 'data-t': String(open) },
|
||||
stepper ? el('div', { class: 'pplus-steps-bar' },
|
||||
el('span', { class: 'pplus-chip pplus-chip-asm' }, 'x86-64'),
|
||||
btn('first', '⏮', 'First step'), btn('back', '◀', 'Back one step'), btn('next', '▶', 'One step'), btn('last', '⏭', 'Last step'), btn('play', 'Play', 'Play the run'),
|
||||
el('input', { type: 'range', class: 'pplus-steps-slider', min: '0', max: String(shown.length - 1), value: String(shown.indexOf(open)), 'aria-label': 'step' }),
|
||||
el('span', { class: 'pplus-steps-count' }, `${open} / ${count}`)) : null,
|
||||
el('div', { class: 'pplus-hw-now' }, nowText(steps[shown.indexOf(open)], open), el('span', { class: 'pplus-muted pplus-hw-machine' }, ` · ${machineLabel(session.state.machine)} machine`)),
|
||||
el('div', { class: `pplus-hw-body${listing ? ' has-listing' : ''}` }, listing, grid),
|
||||
stride > 1 ? el('p', { class: 'pplus-note' }, `The run takes ${count} steps; every ${stride}${stride === 2 ? 'nd' : stride === 3 ? 'rd' : 'th'} is drawn (max="${max}").`) : null,
|
||||
stepper ? el('script', { type: 'application/json', class: 'pplus-hw-data' }, JSON.stringify(data).replace(/</g, '\\u003c')) : null);
|
||||
|
||||
const markdown = machineMarkdown(ids, trace, open);
|
||||
return { node, markdown, warnings, data };
|
||||
}
|
||||
|
||||
/**
|
||||
* A course view's own controls (the core's "cycle ▸", a view's toggles) act on the live widget; in a drawing they
|
||||
* would do nothing, so the drawing leaves them out. The view's markup is its own output: plain buttons, inputs and
|
||||
* menus, never nested.
|
||||
*/
|
||||
export function inert(html: string): string {
|
||||
return html.replace(/<button\b[^>]*>[\s\S]*?<\/button>/g, '').replace(/<select\b[^>]*>[\s\S]*?<\/select>/g, '').replace(/<input\b[^>]*>/g, '');
|
||||
}
|
||||
|
||||
export const nowText = (s: { x: string } | undefined, t: number): string => (t === 0 ? 'Before the first instruction.' : `Step ${t}: ${s?.x ?? ''}`);
|
||||
|
||||
/** Put each card's drawing for the opening step into the serialized markup (see machineBoard). */
|
||||
export function spliceFrames(html: string, node: HTMLElement): string {
|
||||
const holders = [...node.querySelectorAll('[data-hw-frame]')];
|
||||
let i = 0;
|
||||
return html.replace(/<div class="a86 board-a86" data-hw-frame=""><\/div>/g, (m) => {
|
||||
const h = holders[i++] as any;
|
||||
return h?.__html ? m.replace('></div>', `>${h.__html}</div>`) : m;
|
||||
});
|
||||
}
|
||||
|
||||
/** In a format other than HTML: the registers the run wrote, at the step shown, and what each view is. */
|
||||
function machineMarkdown(ids: BoardViewId[], trace: any, t: number): string {
|
||||
const f = boardFrame(trace, t);
|
||||
const regs = new Set<string>();
|
||||
for (const s of trace.steps.slice(0, t)) for (const r of s.diff?.regs ?? []) regs.add(r.name);
|
||||
const hex = (v: unknown) => { try { return '0x' + BigInt.asUintN(64, BigInt(v as any)).toString(16); } catch { return String(v); } };
|
||||
const rows = [...regs].map((r) => `| ${r} | ${hex(f.state.regs[r])} |`);
|
||||
return [`*The machine at step ${t} of ${trace.count}${f.last ? `, after \`${String(f.last.instr.text).trim().replace(/\s+/g, ' ')}\`` : ''}.*`, '',
|
||||
rows.length ? ['| register | value |', '|---|---|', ...rows].join('\n') : '',
|
||||
'', `*Drawn in the HTML version of this page: ${ids.map((id) => boardView(id)!.label).join(', ')}.*`].join('\n');
|
||||
}
|
||||
|
||||
export const HW_VIEW_LIST = BOARD_VIEWS.filter((v) => v.needs === 'asm');
|
||||
@@ -0,0 +1,73 @@
|
||||
// SPDX-FileCopyrightText: 2026 Scientific Computing Studio, LLC
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
/**
|
||||
* A program file as a Quarto page keeps it beside the .qmd: which pane it fills, the header lines the page's
|
||||
* checker reads (`// CALL:`, `// INPUT:`, `// EXPECT:` ...), and the text a reader is shown, without them.
|
||||
*
|
||||
* The rules are the shortcode's (quarto/_extensions/pplus/pplus.lua) and scripts/check-pages.mjs's:
|
||||
* lingo, pseudo, speco `// KEY: value` anywhere in the file
|
||||
* matho (.tex) `% KEY: value`
|
||||
* Mojo the leading block of `# key: value` comments (mojo/local/'s corpus header, or
|
||||
* `# EXPECT:` lines); a `# note:` further down belongs to the program
|
||||
* DOM-free; tests/quarto-render.test.mjs checks it.
|
||||
*/
|
||||
import type { LangId } from '#core/common/types.js';
|
||||
|
||||
export interface ProgramHeader {
|
||||
call?: string;
|
||||
input: string[];
|
||||
expect: string[];
|
||||
errors?: number;
|
||||
stops?: string;
|
||||
questions: string[];
|
||||
}
|
||||
|
||||
/** The pane a file fills, from its extension. */
|
||||
export function langOfFile(name: string): LangId | null {
|
||||
const ext = /\.([a-z0-9]+)$/i.exec(name)?.[1]?.toLowerCase();
|
||||
switch (ext) {
|
||||
case 'lingo': return 'lingo';
|
||||
case 'tex': case 'matho': return 'matho';
|
||||
case 'pseudo': return 'pseudo';
|
||||
case 'speco': return 'speco';
|
||||
case 'mojo': case '🔥': return 'mojo';
|
||||
case 'asm': case 's': return 'asm';
|
||||
default: return null;
|
||||
}
|
||||
}
|
||||
|
||||
// `# expect-stdout:` is the corpus header's spelling of EXPECT (mojo/local/, mojo/stress/), so an exported program keeps its check
|
||||
const HEADER = /^\s*(?:\/\/|%|#)\s*(CALL|INPUT|EXPECT|ERRORS|QUESTION|STOPS|expect-stdout):\s?(.*)$/;
|
||||
|
||||
/** The header lines of a program file (the same lines scripts/check-pages.mjs reads). */
|
||||
export function programHeader(text: string): ProgramHeader {
|
||||
const h: ProgramHeader = { input: [], expect: [], questions: [] };
|
||||
for (const line of text.split('\n')) {
|
||||
const m = HEADER.exec(line);
|
||||
if (!m) continue;
|
||||
const v = m[2];
|
||||
if (m[1] === 'CALL') h.call = v.trim();
|
||||
else if (m[1] === 'INPUT') h.input.push(v);
|
||||
else if (m[1] === 'EXPECT' || m[1] === 'expect-stdout') h.expect.push(v);
|
||||
else if (m[1] === 'ERRORS') h.errors = Number(v);
|
||||
else if (m[1] === 'QUESTION') h.questions.push(v.trim());
|
||||
else if (m[1] === 'STOPS') h.stops = v.trim();
|
||||
}
|
||||
return h;
|
||||
}
|
||||
|
||||
/** The file as a page shows it and a pane holds it: the header lines removed, blank lines trimmed at both ends. */
|
||||
export function listingText(text: string, lang: LangId): string {
|
||||
const out: string[] = [];
|
||||
let head = lang === 'mojo';
|
||||
for (const line of text.replace(/\r\n?/g, '\n').split('\n')) {
|
||||
if (head) {
|
||||
if (/^#\s*[\w-]+:/.test(line)) continue;
|
||||
if (!line.trim() && !out.length) continue;
|
||||
head = false;
|
||||
}
|
||||
if (lang !== 'mojo' && /^\s*(?:\/\/|%)\s*[A-Z]+:/.test(line)) continue;
|
||||
out.push(line);
|
||||
}
|
||||
return out.join('\n').replace(/^\n+/, '').replace(/\n+$/, '');
|
||||
}
|
||||
@@ -0,0 +1,512 @@
|
||||
// SPDX-FileCopyrightText: 2026 Scientific Computing Studio, LLC
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
/**
|
||||
* The static views of the Quarto extension: a program from the files beside a page, run by the app's own engines
|
||||
* when the page is rendered, and drawn by the app's own views (src/ui/views/) as HTML that needs no iframe and no
|
||||
* network. `quarto render` reaches this through quarto/_extensions/pplus/render.mjs, under the small document of
|
||||
* ./dom.ts; the app's "With Quarto" gallery (src/ui/quarto.ts) calls it in the browser, with the real one, so the
|
||||
* gallery shows exactly what a page gets.
|
||||
*
|
||||
* run what the program prints (and returns), checked against its EXPECT lines
|
||||
* steps the listing with a stepper: every step, the line it ran, the values after it (pplus.js steps it)
|
||||
* table the table of values: a column per step that changed something, a row per name
|
||||
* flow the flowchart of the routine, shaded by how often each line ran
|
||||
* data the data-flow graph of the routine
|
||||
* life each Mojo value's lifetime: made, copied, moved, destroyed
|
||||
* proof the claims of the speco (or the pseudo's ENSUREs), proved, broken or open
|
||||
* tests the fuzzer's report for every routine
|
||||
* check the checker's findings for each file, on its own lines
|
||||
* translate the procedure in every notation the hub can write it in, Mojo generated from the pseudo
|
||||
* machine the x86-64 run on the model machine: instructions, cycles, cache misses
|
||||
* hw the Hardware area's board over an x86-64 run: registers, memory, caches, pipeline, the core...,
|
||||
* steppable (./machine.ts)
|
||||
*
|
||||
* Every view returns HTML for an HTML page and Markdown for any other format (a PDF, a Word file), so a page
|
||||
* renders everywhere; the Markdown says plainly what only the HTML can show.
|
||||
*/
|
||||
import { el, add } from '../ui/dom.js';
|
||||
import { Session } from '../core/session.js';
|
||||
import { emptyState, type PlayState } from '../core/state.js';
|
||||
import { LANG_NAMES, type LangId } from '#core/common/types.js';
|
||||
import { SERVICES } from '#core/services/index.js';
|
||||
import { SyncHub, mojoFromPseudo, LINKED } from '#core/sync/hub.js';
|
||||
import { runColumns, defaultFollow, runRows, valuesAt, type RunRow } from '#core/common/runview.js';
|
||||
import { familyOf } from '../ui/stepkinds.js';
|
||||
import { flowView, dataFlowView, traceTableView } from '../ui/views/viz.js';
|
||||
import { problemsView, proofView, machineView } from '../ui/views/panels.js';
|
||||
import { testsView } from '../ui/views/tests.js';
|
||||
import { lifetimesView } from '../ui/views/lifetimes.js';
|
||||
import { MOJO_VERSION } from '#core/mojo/generated/pin.js';
|
||||
import { listingText, programHeader, type ProgramHeader } from './program.js';
|
||||
import { machineBoard, spliceFrames } from './machine.js';
|
||||
|
||||
export const STATIC_VIEWS = ['run', 'steps', 'table', 'flow', 'data', 'life', 'proof', 'tests', 'check', 'translate', 'machine', 'hw'] as const;
|
||||
export type StaticView = typeof STATIC_VIEWS[number];
|
||||
export const isStaticView = (v: unknown): v is StaticView => (STATIC_VIEWS as readonly string[]).includes(v as string);
|
||||
|
||||
const PANES: LangId[] = ['lingo', 'matho', 'pseudo', 'speco', 'mojo', 'asm'];
|
||||
|
||||
/** What a page asks for: one view of the program in `files` (each file's text as it is on disk, header and all). */
|
||||
export interface RenderRequest {
|
||||
view: StaticView;
|
||||
files: Partial<Record<LangId, string>>;
|
||||
/** The pane the run reads (default: the first of lingo, matho, pseudo, mojo, asm given; speco runs as its pseudo). */
|
||||
lang?: LangId;
|
||||
/** The call, and the lines INPUT reads; by default the files' own `// CALL:` and `// INPUT:` lines. */
|
||||
call?: string | null;
|
||||
input?: string[];
|
||||
setup?: string;
|
||||
machine?: string;
|
||||
/** The step a stepper starts on, and where the flowchart and the table of values stop (default: the end). */
|
||||
t?: number;
|
||||
title?: string;
|
||||
/** translate: the notations to show (default: every one the procedure has, and Mojo). */
|
||||
to?: LangId[];
|
||||
/** steps: the most steps kept for the stepper (default 400). */
|
||||
max?: number;
|
||||
/** steps, table: the variables to show, as written in the program (default: the routine that does the most work). */
|
||||
follow?: string[];
|
||||
/** hw: the machine views to show (their shortcode names or board ids), or a preset of the board (regs, caches, pipeline, chip). */
|
||||
hw?: string[];
|
||||
preset?: string;
|
||||
/** hw: false leaves out the x86-64 listing; stepper false draws only the step `t`. */
|
||||
listing?: boolean;
|
||||
stepper?: boolean;
|
||||
/** A run of the Mojo file by a real compiler (render.mjs does it when `mojo` is on the PATH). */
|
||||
compiled?: { stdout: string; stderr: string; status: number | null; version: string } | null;
|
||||
}
|
||||
|
||||
export interface TranslatedPane { lang: LangId; label: string; text: string; authored: boolean; generated: boolean; note?: string; /** For a generated pane: the notation it was written from. */ from?: LangId }
|
||||
|
||||
export interface RenderResult {
|
||||
view: StaticView;
|
||||
/** The language that ran or was drawn. */
|
||||
lang: LangId | null;
|
||||
/** The view as an element of whichever document is installed, and as markup. */
|
||||
node: HTMLElement;
|
||||
html: string;
|
||||
markdown: string;
|
||||
/** Things the author should know (stderr in `quarto render`): a run that does not print its EXPECT lines, a missing piece. */
|
||||
warnings: string[];
|
||||
/** run: what the program printed against what its EXPECT lines say. */
|
||||
expect?: { want: string[]; got: string[]; ok: boolean };
|
||||
/** translate: each notation's text. */
|
||||
panes?: TranslatedPane[];
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* The session */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
interface Prepared { session: Session; header: ProgramHeader; given: LangId[]; sources: Partial<Record<LangId, string>> }
|
||||
|
||||
function prepare(req: RenderRequest): Prepared {
|
||||
const sources: Partial<Record<LangId, string>> = {};
|
||||
const given: LangId[] = [];
|
||||
for (const l of PANES) {
|
||||
const text = req.files[l];
|
||||
if (typeof text !== 'string') continue;
|
||||
sources[l] = listingText(text, l);
|
||||
given.push(l);
|
||||
}
|
||||
const runnable = (['lingo', 'matho', 'pseudo', 'mojo', 'asm'] as LangId[]).find((l) => given.includes(l)) ?? given[0] ?? 'pseudo';
|
||||
const lang = req.lang && given.includes(req.lang) ? req.lang : runnable;
|
||||
// the header of the file that runs comes first; another file's fills in what it leaves out
|
||||
const order = [lang, ...given.filter((l) => l !== lang)];
|
||||
const header: ProgramHeader = { input: [], expect: [], questions: [] };
|
||||
for (const l of order) {
|
||||
const h = programHeader(req.files[l] ?? '');
|
||||
header.call ??= h.call; header.errors ??= h.errors; header.stops ??= h.stops;
|
||||
if (!header.input.length) header.input = h.input;
|
||||
if (!header.expect.length) header.expect = h.expect;
|
||||
header.questions.push(...h.questions);
|
||||
}
|
||||
const state: PlayState = { ...emptyState(), sources, lang, view: 'trace' };
|
||||
const call = req.call !== undefined ? req.call : header.call;
|
||||
if (call) state.call = call;
|
||||
const input = req.input ?? header.input;
|
||||
if (input.length) state.input = input.join('\n');
|
||||
if (req.setup) state.setup = listingText(req.setup, 'asm');
|
||||
if (req.machine) state.machine = req.machine;
|
||||
if (typeof req.t === 'number' && req.t >= 0) state.t = Math.floor(req.t);
|
||||
if (req.title) state.title = req.title;
|
||||
return { session: new Session(state), header, given, sources };
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* Small pieces */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
/** Code, highlighted by the pane's own highlighter, one `.pplus-ln` per line (`data-line` is 1-based). */
|
||||
export function highlighted(text: string, lang: LangId, opts: { numbers?: boolean } = {}): HTMLElement {
|
||||
const svc = SERVICES[lang];
|
||||
const rows = text.split('\n');
|
||||
const doc = svc.tokenizeLines ? svc.tokenizeLines(text) : null;
|
||||
// focusable, so a reader with only a keyboard can scroll a listing wider or taller than its box
|
||||
const pre = el('pre', { class: `pplus-code lang-${lang}`, tabindex: '0' });
|
||||
rows.forEach((line, i) => {
|
||||
const ln = el('span', { class: 'pplus-ln', 'data-line': String(i + 1) });
|
||||
if (opts.numbers) add(ln, el('span', { class: 'pplus-lno', 'aria-hidden': 'true' }, String(i + 1)));
|
||||
const toks = doc ? doc[i] ?? [] : svc.tokenize ? svc.tokenize(line) : [{ text: line, cls: '' }];
|
||||
for (const t of toks) add(ln, t.cls ? el('span', { class: t.cls }, t.text) : t.text);
|
||||
if (!line) add(ln, ' ');
|
||||
add(pre, ln);
|
||||
if (i < rows.length - 1) add(pre, '\n');
|
||||
});
|
||||
return pre;
|
||||
}
|
||||
|
||||
const chip = (lang: LangId) => el('span', { class: `pplus-chip pplus-chip-${lang}` }, LANG_NAMES[lang]);
|
||||
|
||||
function head(...parts: Array<HTMLElement | string | null>): HTMLElement {
|
||||
return el('div', { class: 'pplus-head' }, ...parts);
|
||||
}
|
||||
|
||||
/** A view built for a screen, made for a page: controls that need the app (buttons, inputs, menus) are taken out, and a link-styled line reference becomes plain text. */
|
||||
export function freeze(root: Element): void {
|
||||
for (const s of [...root.querySelectorAll('select')]) {
|
||||
const opt = (s as HTMLSelectElement).options[(s as HTMLSelectElement).selectedIndex] ?? (s as HTMLSelectElement).options[0];
|
||||
s.replaceWith(el('span', { class: 'pplus-picked' }, opt?.textContent ?? ''));
|
||||
}
|
||||
for (const b of [...root.querySelectorAll('button')]) {
|
||||
if (b.classList.contains('linkish')) b.replaceWith(el('span', { class: b.className.replace('linkish', 'pplus-ref') }, b.textContent ?? ''));
|
||||
else if (b.classList.contains('btn-option')) b.replaceWith(el('span', { class: 'pplus-option' }, b.textContent ?? ''));
|
||||
else if (b.classList.contains('life-mark')) b.replaceWith(el('span', { class: b.className, title: b.getAttribute('title') ?? '', style: b.getAttribute('style') ?? '' }));
|
||||
else b.remove();
|
||||
}
|
||||
for (const i of [...root.querySelectorAll('input')]) i.remove();
|
||||
for (const l of [...root.querySelectorAll('.tool-label')]) l.remove();
|
||||
// what the app says about stepping, which a page does not do
|
||||
for (const x of [...root.querySelectorAll('.fuzz-bar, .viz-step-note')]) x.remove();
|
||||
for (const x of [...root.querySelectorAll('[title=""]')]) x.removeAttribute('title');
|
||||
}
|
||||
|
||||
const mdEscape = (s: string) => s.replace(/\|/g, '\\|').replace(/\n/g, ' ');
|
||||
const fence = (text: string, cls = '') => { const ticks = /```/.test(text) ? '````' : '```'; return `${ticks}${cls}\n${text}\n${ticks}`; };
|
||||
function mdTable(headRow: string[], rows: string[][]): string {
|
||||
return [`| ${headRow.map(mdEscape).join(' | ')} |`, `|${headRow.map(() => '---').join('|')}|`, ...rows.map((r) => `| ${r.map((c) => mdEscape(c || ' ')).join(' | ')} |`)].join('\n');
|
||||
}
|
||||
|
||||
function result(view: StaticView, lang: LangId | null, node: HTMLElement, markdown: string, warnings: string[] = [], extra: Partial<RenderResult> = {}): RenderResult {
|
||||
node.classList.add('pplus-static', `pplus-v-${view}`);
|
||||
node.setAttribute('data-pplus-view', view);
|
||||
return { view, lang, node, html: node.outerHTML, markdown, warnings, ...extra };
|
||||
}
|
||||
|
||||
/** A view of the app's, drawn into a fresh element and frozen for the page. */
|
||||
function appView(draw: (host: HTMLElement) => unknown, cls: string): HTMLElement {
|
||||
const host = el('div', { class: `view ${cls}` });
|
||||
draw(host);
|
||||
freeze(host);
|
||||
return host;
|
||||
}
|
||||
|
||||
const noHooks = { reveal: () => { /* a page has no editor to move */ }, fix: () => { /* nor one to fix */ } };
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* The views */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
export function renderStatic(req: RenderRequest): RenderResult {
|
||||
if (!isStaticView(req.view)) throw new Error(`unknown view "${req.view}": the static views are ${STATIC_VIEWS.join(', ')}`);
|
||||
const p = prepare(req);
|
||||
if (!p.given.length) return result(req.view, null, el('div', {}, el('p', { class: 'pplus-note' }, 'No program: give a file (pseudo=, lingo=, matho=, speco=, mojo= or asm=).')), '*No program was given.*', ['no program file was given']);
|
||||
switch (req.view) {
|
||||
case 'run': return runOf(p, req);
|
||||
case 'steps': return stepsOf(p, req);
|
||||
case 'table': return tableOf(p);
|
||||
case 'flow': case 'data': return graphOf(p, req.view);
|
||||
case 'life': return lifeOf(p);
|
||||
case 'proof': return proofOf(p);
|
||||
case 'tests': return testsOf(p);
|
||||
case 'check': return checkOf(p);
|
||||
case 'translate': return translateOf(p, req);
|
||||
case 'machine': return machineOf(p);
|
||||
case 'hw': return hwOf(p, req);
|
||||
}
|
||||
}
|
||||
|
||||
/* ---------- run ---------- */
|
||||
|
||||
function runOf(p: Prepared, req: RenderRequest): RenderResult {
|
||||
const { session, header } = p;
|
||||
const warnings: string[] = [];
|
||||
const lang = session.traceLang();
|
||||
const trace = session.trace();
|
||||
const call = lang !== 'mojo' && lang !== 'asm' ? session.callText() : null;
|
||||
const node = el('div', {});
|
||||
const compiled = lang === 'mojo' ? req.compiled ?? null : null;
|
||||
let got: string[];
|
||||
let who: string;
|
||||
if (compiled) {
|
||||
got = compiled.stdout.replace(/\n$/, '').split('\n').filter((l, i, a) => !(a.length === 1 && l === ''));
|
||||
who = `${compiled.version}, on the machine that rendered this page`;
|
||||
} else {
|
||||
got = trace ? [...trace.output] : [];
|
||||
who = lang === 'mojo' ? `Programming+'s Mojo interpreter (modeled on Mojo ${MOJO_VERSION}; not the compiler)` : lang === 'asm' ? 'the model x86-64 machine' : `Programming+'s ${LANG_NAMES[lang]} interpreter`;
|
||||
}
|
||||
add(node, head(chip(lang), call ? el('code', { class: 'pplus-call' }, call) : null, el('span', { class: 'pplus-muted' }, trace ? `${trace.count} step${trace.count === 1 ? '' : 's'}` : ''), el('span', { class: 'pplus-spacer' }), el('span', { class: 'pplus-muted pplus-who' }, who)));
|
||||
if (!trace && !compiled) {
|
||||
const why = session.runError ?? (session.allDiagnostics().find((d) => d.severity === 'error')?.message ? `It does not run yet: ${session.allDiagnostics().find((d) => d.severity === 'error')!.message}` : 'There is nothing to run.');
|
||||
add(node, el('p', { class: 'pplus-err' }, why));
|
||||
warnings.push(`run: ${why}`);
|
||||
// a program with EXPECT lines that does not run does not print them: pplus-strict stops the render on it
|
||||
return result('run', lang, node, `*${why}*`, warnings, header.expect.length ? { expect: { want: header.expect, got: [], ok: false } } : undefined);
|
||||
}
|
||||
add(node, el('pre', { class: 'pplus-out' }, got.length ? got.join('\n') : el('span', { class: 'pplus-muted' }, '(printed nothing)')));
|
||||
let errText: string | null = null;
|
||||
if (compiled && compiled.status !== 0) errText = `exited with status ${compiled.status}${compiled.stderr.trim() ? `: ${compiled.stderr.trim().split('\n').slice(0, 6).join('\n')}` : ''}`;
|
||||
else if (!compiled && trace?.error) errText = `stopped${trace.error.line ? ` at line ${trace.error.line}` : ''}: ${trace.error.message}`;
|
||||
if (errText) add(node, el('p', { class: header.stops ? 'pplus-note' : 'pplus-err' }, `The run ${errText}`));
|
||||
if (trace?.truncated) add(node, el('p', { class: 'pplus-note' }, 'The run was cut short after the step limit.'));
|
||||
let expect: RenderResult['expect'];
|
||||
if (header.expect.length) {
|
||||
const ok = JSON.stringify(got) === JSON.stringify(header.expect);
|
||||
expect = { want: header.expect, got, ok };
|
||||
add(node, el('div', { class: `pplus-expect ${ok ? 'is-ok' : 'is-bad'}` }, ok
|
||||
? `✓ prints the ${header.expect.length} line${header.expect.length === 1 ? '' : 's'} its EXPECT header says`
|
||||
: el('span', {}, '✗ does not print what its EXPECT header says. Expected:', el('pre', { class: 'pplus-out' }, header.expect.join('\n')))));
|
||||
if (!ok) warnings.push(`run: printed ${JSON.stringify(got)}, its EXPECT lines say ${JSON.stringify(header.expect)}`);
|
||||
}
|
||||
if (compiled && trace && JSON.stringify(trace.output) !== JSON.stringify(got)) warnings.push('run: Programming+\'s Mojo interpreter printed something else than the compiler; the page shows the compiler\'s output');
|
||||
const md = [`${LANG_NAMES[lang]}${call ? ` \`${call}\`` : ''}, run by ${who}:`, '', fence(got.join('\n') || '(printed nothing)'), errText ? `\n*The run ${errText}*` : ''].join('\n');
|
||||
return result('run', lang, node, md, warnings, { expect });
|
||||
}
|
||||
|
||||
/* ---------- steps ---------- */
|
||||
|
||||
/** The stepper's data, read by pplus.js: one row per step, and a value per followed variable after it. */
|
||||
export interface StepsData {
|
||||
lang: LangId;
|
||||
count: number;
|
||||
t: number;
|
||||
cols: Array<{ label: string; type: string }>;
|
||||
/** l: the line the step ran; x: what it did; f: its kind (write, decision, loop, call, return, io, life, error); w: what it wrote; c: each column's value after it (null: not in scope); cw: the columns it wrote; o: what it printed. */
|
||||
rows: Array<{ l: number | null; x: string; f: string; w: string[]; c: Array<string | null>; cw: number[]; o: string[] }>;
|
||||
/** The values before the first step. */
|
||||
c0: Array<string | null>;
|
||||
error: string | null;
|
||||
truncated: boolean;
|
||||
}
|
||||
|
||||
const hex = (v: unknown): string => { try { return '0x' + BigInt.asUintN(64, BigInt(v as any)).toString(16); } catch { return String(v); } };
|
||||
|
||||
function stepsData(session: Session, req: RenderRequest): StepsData | null {
|
||||
const trace = session.trace();
|
||||
if (!trace) return null;
|
||||
const max = Math.max(10, Math.min(req.max ?? 400, 5000));
|
||||
const n = Math.min(trace.count, max);
|
||||
if (trace.lang === 'asm') {
|
||||
const steps = trace.steps as any[];
|
||||
const states = trace.states as any[];
|
||||
const regs: string[] = [];
|
||||
for (const s of steps.slice(0, n)) for (const r of s.diff?.regs ?? []) if (!regs.includes(r.name)) regs.push(r.name);
|
||||
const at = (i: number) => regs.map((r) => (states[i]?.regs?.[r] !== undefined ? hex(states[i].regs[r]) : null));
|
||||
return {
|
||||
lang: 'asm', count: n, t: Math.min(req.t ?? 0, n), cols: regs.map((r) => ({ label: r, type: 'register' })), c0: at(0),
|
||||
rows: steps.slice(0, n).map((s, i) => {
|
||||
const wrote = (s.diff?.regs ?? []).map((r: any) => r.name);
|
||||
return { l: s.instr.lineNo + 1, x: s.instr.text, f: s.branch ? 'decision' : wrote.length ? 'write' : 'other', w: [...wrote, ...(s.diff?.mem?.length ? ['memory'] : [])], c: at(i + 1), cw: wrote.map((r: string) => regs.indexOf(r)), o: s.diff?.out ? [s.diff.out] : [] };
|
||||
}),
|
||||
error: trace.error?.message ?? null, truncated: trace.truncated || trace.count > n,
|
||||
};
|
||||
}
|
||||
const cols = runColumns(trace);
|
||||
let follow = defaultFollow(cols, 6);
|
||||
if (req.follow?.length) {
|
||||
const want = req.follow.map((f) => f.toLowerCase());
|
||||
const picked = cols.filter((c) => want.includes(c.name.toLowerCase()) || want.includes(c.key.toLowerCase())).map((c) => c.key);
|
||||
if (picked.length) follow = picked;
|
||||
}
|
||||
const byKey = new Map(cols.map((c) => [c.key, c]));
|
||||
const many = new Set(follow.map((k) => k.split('.')[0])).size > 1;
|
||||
const rows: RunRow[] = runRows(trace, follow, 0, n);
|
||||
// what the run prints after its last step (a call's result, "F returned 3") belongs to that step
|
||||
const printed = rows.reduce((k, r) => k + r.printed.length, 0);
|
||||
if (n === trace.count && rows.length && printed < trace.output.length) rows[rows.length - 1].printed.push(...trace.output.slice(printed));
|
||||
return {
|
||||
lang: trace.lang, count: n, t: Math.min(req.t ?? 0, n),
|
||||
cols: follow.map((k) => { const c = byKey.get(k)!; return { label: many ? `${c.fn}.${c.name}` : c.name, type: c.type }; }),
|
||||
c0: valuesAt(trace, follow, 0).map((v) => v.text),
|
||||
rows: rows.map((r) => ({ l: r.line, x: r.text, f: familyOf({ kind: r.kind, text: r.text, writes: r.writes }, trace.lang), w: r.writes, c: follow.map((k) => r.cells[k]?.text ?? null), cw: follow.map((k, i) => (r.cells[k]?.wrote ? i : -1)).filter((i) => i >= 0), o: r.printed })),
|
||||
error: trace.error?.message ?? null, truncated: trace.truncated || trace.count > n,
|
||||
};
|
||||
}
|
||||
|
||||
/** The stepper's panels at position `t` (after t steps), drawn the way pplus.js redraws them; also the page without script. */
|
||||
export function stepsPanel(data: StepsData, t: number): { now: string; vals: Array<string | null>; wrote: number[]; out: string[]; next: number | null; last: number | null } {
|
||||
const last = t > 0 ? data.rows[t - 1] : null;
|
||||
const next = t < data.count ? data.rows[t] : null;
|
||||
const out = data.rows.slice(0, t).flatMap((r) => r.o);
|
||||
const now = t === 0 ? (data.count ? 'Before the first step.' : 'The program takes no steps.') : `Step ${t}: ${last!.x}${last!.w.length ? ` — writes ${last!.w.join(', ')}` : ''}`;
|
||||
return { now, vals: last ? last.c : data.c0, wrote: last ? last.cw : [], out, next: next?.l ?? null, last: last?.l ?? null };
|
||||
}
|
||||
|
||||
function stepsOf(p: Prepared, req: RenderRequest): RenderResult {
|
||||
const { session } = p;
|
||||
const data = stepsData(session, req);
|
||||
const lang = session.traceLang();
|
||||
if (!data) {
|
||||
const why = session.runError ?? 'It does not run yet; the check view lists what the checker found.';
|
||||
return result('steps', lang, el('div', {}, el('p', { class: 'pplus-err' }, why)), `*${why}*`, [`steps: ${why}`]);
|
||||
}
|
||||
const source = session.source(data.lang);
|
||||
const t = data.t;
|
||||
const at = stepsPanel(data, t);
|
||||
const code = highlighted(source, data.lang, { numbers: true });
|
||||
for (const ln of [...code.querySelectorAll('.pplus-ln')]) {
|
||||
const n = Number(ln.getAttribute('data-line'));
|
||||
if (n === at.next) ln.classList.add('is-next');
|
||||
if (n === at.last) ln.classList.add('is-last');
|
||||
}
|
||||
const btn = (go: string, label: string, title: string) => el('button', { type: 'button', class: 'pplus-btn', 'data-go': go, title, 'aria-label': title }, label);
|
||||
const vars = el('table', { class: 'pplus-vars' });
|
||||
data.cols.forEach((c, i) => add(vars, el('tr', { class: at.wrote.includes(i) ? 'is-wrote' : '' }, el('th', { title: c.type }, c.label), el('td', { 'data-col': String(i) }, at.vals[i] ?? '—'))));
|
||||
const json = JSON.stringify(data).replace(/</g, '\\u003c');
|
||||
const node = el('div', { 'data-count': String(data.count), 'data-t': String(t) },
|
||||
el('div', { class: 'pplus-steps-bar' },
|
||||
chip(data.lang),
|
||||
btn('first', '⏮', 'First step'), btn('back', '◀', 'Back one step'), btn('next', '▶', 'One step'), btn('last', '⏭', 'Last step'), btn('play', 'Play', 'Play the run'),
|
||||
el('input', { type: 'range', class: 'pplus-steps-slider', min: '0', max: String(data.count), value: String(t), 'aria-label': 'step' }),
|
||||
el('span', { class: 'pplus-steps-count' }, `${t} / ${data.count}`)),
|
||||
el('div', { class: 'pplus-steps-body' },
|
||||
el('div', { class: 'pplus-steps-code' }, code),
|
||||
el('div', { class: 'pplus-steps-side' },
|
||||
el('div', { class: 'pplus-steps-now' }, at.now),
|
||||
data.cols.length ? vars : el('p', { class: 'pplus-muted' }, 'No variables to follow.'),
|
||||
el('div', { class: 'pplus-steps-out-h' }, 'printed so far'),
|
||||
el('pre', { class: 'pplus-out pplus-steps-out' }, at.out.join('\n')))),
|
||||
data.error ? el('p', { class: 'pplus-err' }, `The run stops: ${data.error}`) : null,
|
||||
data.truncated ? el('p', { class: 'pplus-note' }, `The first ${data.count} steps are shown.`) : null,
|
||||
el('script', { type: 'application/json', class: 'pplus-steps-data' }, json));
|
||||
const md = [`${LANG_NAMES[data.lang]}, ${data.count} steps:`, '', mdTable(['step', 'line', 'what it does', ...data.cols.map((c) => c.label)], data.rows.slice(0, 60).map((r, i) => [String(i + 1), String(r.l ?? ''), r.x, ...r.c.map((v) => v ?? '')]))].join('\n') + (data.count > 60 ? `\n\n*…and ${data.count - 60} more steps in the HTML version.*` : '');
|
||||
return result('steps', data.lang, node, md);
|
||||
}
|
||||
|
||||
/* ---------- table, flow, data, life ---------- */
|
||||
|
||||
function tableOf(p: Prepared): RenderResult {
|
||||
const { session } = p;
|
||||
const node = appView((h) => traceTableView(session, h), 'view-table');
|
||||
const trace = session.trace();
|
||||
let md = '*The table of values needs a run that works.*';
|
||||
if (trace && trace.lang !== 'asm') {
|
||||
const follow = defaultFollow(runColumns(trace), 8);
|
||||
const rows = runRows(trace, follow, 0, trace.count, { onlyWrites: true }).slice(0, 80);
|
||||
md = mdTable(['step', 'line', ...follow.map((k) => k.slice(k.indexOf('.') + 1)), 'printed'], rows.map((r) => [String(r.step + 1), String(r.line ?? ''), ...follow.map((k) => (r.cells[k]?.wrote ? r.cells[k].text ?? '' : '')), r.printed.join(' ⏎ ')]));
|
||||
}
|
||||
return result('table', trace?.lang ?? session.traceLang(), node, md);
|
||||
}
|
||||
|
||||
function graphOf(p: Prepared, view: 'flow' | 'data'): RenderResult {
|
||||
const { session } = p;
|
||||
// the flowchart and the data flow draw the pseudo (or the Mojo); a lingo or matho program is drawn as its pseudo
|
||||
if (session.state.lang !== 'mojo') session.state.lang = 'pseudo';
|
||||
const node = appView((h) => (view === 'flow' ? flowView(session, h) : dataFlowView(session, h)), view === 'flow' ? 'view-flow' : 'view-data');
|
||||
const what = view === 'flow' ? 'flowchart' : 'data-flow graph';
|
||||
return result(view, session.state.lang, node, `*The ${what} of this procedure is drawn in the HTML version of this page.*`);
|
||||
}
|
||||
|
||||
function lifeOf(p: Prepared): RenderResult {
|
||||
const { session } = p;
|
||||
session.state.lang = 'mojo';
|
||||
const node = appView((h) => lifetimesView(session, h), 'view-life');
|
||||
const warnings = p.given.includes('mojo') ? [] : ['life: lifetimes are drawn for a Mojo file (mojo=)'];
|
||||
return result('life', 'mojo', node, '*Each value\'s lifetime is drawn in the HTML version of this page.*', warnings);
|
||||
}
|
||||
|
||||
/* ---------- proof, tests, check ---------- */
|
||||
|
||||
function proofOf(p: Prepared): RenderResult {
|
||||
const { session } = p;
|
||||
session.state.lang = 'pseudo';
|
||||
const node = appView((h) => proofView(session, h, noHooks), 'view-proof');
|
||||
const pr = session.proof();
|
||||
const md = pr ? [`**${pr.report.counts.proved} proved, ${pr.report.counts.broken} broken, ${pr.report.counts.open} open.**`, '', ...pr.report.units.flatMap((u) => u.obligations.map((o) => `- ${o.status}: ${o.label} (line ${(o as any).specoLine ?? (o as any).pseudoLine ?? o.line})`))].join('\n') : '*The proof needs pseudocode that parses.*';
|
||||
return result('proof', 'pseudo', node, md, pr && pr.report.counts.broken ? [`proof: ${pr.report.counts.broken} claim(s) broken`] : []);
|
||||
}
|
||||
|
||||
function testsOf(p: Prepared): RenderResult {
|
||||
const { session } = p;
|
||||
if (session.state.lang !== 'mojo') session.state.lang = 'pseudo';
|
||||
const node = appView((h) => testsView(session, h, noHooks), 'view-tests');
|
||||
const reps = session.tests();
|
||||
const md = reps.length ? reps.map((r) => `- \`${r.name}\`: ${r.failures.length ? `${r.failures.length} way(s) to fail, e.g. \`${r.failures[0].call}\`: ${r.failures[0].message}` : 'no failures'} on ${r.checked} generated inputs`).join('\n') : '*Nothing to test: generated-input testing needs a routine.*';
|
||||
return result('tests', session.state.lang, node, md);
|
||||
}
|
||||
|
||||
function checkOf(p: Prepared): RenderResult {
|
||||
const { session, given } = p;
|
||||
// only the files the page gave: a notation the hub filled in is not the author's to answer for
|
||||
const view = Object.create(session) as Session;
|
||||
(view as any).allDiagnostics = () => given.flatMap((l) => session.diagnostics(l));
|
||||
const node = appView((h) => problemsView(view, h, noHooks), 'view-problems');
|
||||
const diags = given.flatMap((l) => session.diagnostics(l));
|
||||
const md = diags.length ? diags.map((d) => `- **${d.severity}**, ${LANG_NAMES[d.lang]} line ${d.line}: ${d.message}`).join('\n') : '*The checker has nothing to report.*';
|
||||
return result('check', given[0] ?? null, node, md);
|
||||
}
|
||||
|
||||
/* ---------- translate ---------- */
|
||||
|
||||
const LABEL: Record<LangId, string> = { lingo: 'lingo', matho: 'matho', pseudo: 'pseudo', speco: 'speco', mojo: 'Mojo', asm: 'x86-64' };
|
||||
|
||||
function translateOf(p: Prepared, req: RenderRequest): RenderResult {
|
||||
const { sources, given, header } = p;
|
||||
const warnings: string[] = [];
|
||||
const call = req.call !== undefined ? req.call : header.call ?? null;
|
||||
const linkedGiven = given.filter((l) => (LINKED as readonly string[]).includes(l));
|
||||
const panes: TranslatedPane[] = [];
|
||||
let hub: { sources: Partial<Record<LangId, string>>; stale: Partial<Record<LangId, string>>; mojo: string; lead: LangId } | null = null;
|
||||
if (linkedGiven.length) {
|
||||
// the first file the page gave leads, as if typed into its pane; the notations it was not given follow from it
|
||||
// (a file the page gives is always shown as written)
|
||||
const lead = linkedGiven.includes(req.lang as any) ? req.lang! : linkedGiven[0];
|
||||
const r = new SyncHub({ lingo: '', matho: '', pseudo: '', speco: '' }, undefined, { call }).edit(lead as any, sources[lead] ?? '');
|
||||
hub = { sources: r.sources, stale: r.stale, mojo: r.mojo.source, lead };
|
||||
}
|
||||
const want = req.to?.length ? req.to : [...LINKED, 'mojo'] as LangId[];
|
||||
for (const l of want) {
|
||||
if (given.includes(l)) { panes.push({ lang: l, label: LABEL[l], text: sources[l] ?? '', authored: true, generated: false }); continue; }
|
||||
if (l === 'mojo') {
|
||||
const text = hub?.mojo ?? (hub?.sources.pseudo ? mojoFromPseudo(hub.sources.pseudo, call).source : '');
|
||||
if (text.trim()) panes.push({ lang: 'mojo', label: 'Mojo', text, authored: false, generated: true, from: 'pseudo', note: 'Generated from the pseudo: a literal translation, not reviewed for Mojo best practices.' });
|
||||
continue;
|
||||
}
|
||||
if (!hub || !(LINKED as readonly string[]).includes(l)) continue;
|
||||
const text = hub.sources[l] ?? '';
|
||||
const stale = hub.stale[l];
|
||||
if (stale) { panes.push({ lang: l, label: LABEL[l], text: '', authored: false, generated: false, note: stale }); continue; }
|
||||
if (text.trim()) panes.push({ lang: l, label: LABEL[l], text, authored: false, generated: true, from: hub.lead });
|
||||
}
|
||||
// the notations the page gave first, as written; then what was made from them
|
||||
panes.sort((a, b) => Number(b.authored) - Number(a.authored));
|
||||
if (!panes.some((x) => x.text.trim())) warnings.push('translate: nothing to show; give a lingo, matho, pseudo or speco file');
|
||||
const node = el('div', { class: 'pplus-translate-grid' });
|
||||
for (const pane of panes) {
|
||||
add(node, el('div', { class: `pplus-pane pplus-pane-${pane.lang}` },
|
||||
el('div', { class: 'pplus-pane-head' }, chip(pane.lang), pane.authored ? el('span', { class: 'pplus-muted' }, 'as written') : pane.generated ? el('span', { class: 'pplus-tag-generated' }, 'generated') : null),
|
||||
pane.text ? highlighted(pane.text, pane.lang) : null,
|
||||
pane.note ? el('p', { class: pane.text ? 'pplus-muted pplus-small' : 'pplus-note' }, pane.text ? pane.note : `Cannot be written in ${pane.label}: ${pane.note}`) : null));
|
||||
}
|
||||
const md = panes.map((x) => `**${x.label}**${x.generated ? ' (generated)' : ''}\n\n${x.text ? fence(x.text, x.lang === 'matho' ? 'latex' : x.lang) : `*${x.note}*`}`).join('\n\n');
|
||||
return result('translate', panes[0]?.lang ?? null, node, md, warnings, { panes });
|
||||
}
|
||||
|
||||
/* ---------- machine ---------- */
|
||||
|
||||
function machineOf(p: Prepared): RenderResult {
|
||||
const { session } = p;
|
||||
session.state.lang = 'asm';
|
||||
const node = appView((h) => machineView(session, h), 'view-asm');
|
||||
const rows = [...node.querySelectorAll('.perf-tbl tr')].map((tr) => [...tr.children].map((c) => (c.textContent ?? '').trim()));
|
||||
const md = rows.length ? mdTable(['', 'value'], rows) : '*The machine view needs an x86-64 file that assembles (asm=).*';
|
||||
return result('machine', 'asm', node, md, p.given.includes('asm') ? [] : ['machine: the machine view needs an x86-64 file (asm=)']);
|
||||
}
|
||||
|
||||
/* ---------- hw: the machine board ---------- */
|
||||
|
||||
function hwOf(p: Prepared, req: RenderRequest): RenderResult {
|
||||
const b = machineBoard(p.session, { views: req.hw, preset: req.preset, t: req.t, max: req.max, listing: req.listing, stepper: req.stepper });
|
||||
const r = result('hw', 'asm', b.node, b.markdown, b.warnings);
|
||||
return { ...r, html: spliceFrames(r.html, b.node) };
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
// SPDX-FileCopyrightText: 2026 Scientific Computing Studio, LLC
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
/**
|
||||
* The shortcodes of the Quarto extension (quarto/_extensions/pplus/pplus.lua), as data: what each is called, what
|
||||
* it shows, and the options it reads. The app's "With Quarto" gallery (src/ui/quarto.ts) is written from this,
|
||||
* scripts/check-pages.mjs reads it to know a shortcode when it sees one, and tests/quarto.test.mjs holds it to the
|
||||
* names pplus.lua returns. DOM-free.
|
||||
*/
|
||||
import type { LangId } from '#core/common/types.js';
|
||||
import type { StaticView, RenderRequest } from './render.js';
|
||||
import { listingText } from './program.js';
|
||||
import { emptyState, type PlayState } from '../core/state.js';
|
||||
import { boardView } from '../core/hardware.js';
|
||||
import { HW_NAMES } from './machine.js';
|
||||
|
||||
export type ShortcodeKind = 'rendered' | 'machine' | 'live' | 'text';
|
||||
|
||||
export interface ShortcodeDef {
|
||||
name: string;
|
||||
kind: ShortcodeKind;
|
||||
/** rendered: the view render.ts draws; live: the embed view (or `any`, chosen by view=). */
|
||||
view?: StaticView | 'playground' | 'any';
|
||||
/** machine: the board view it shows (its pplus-hw-<name>), or none for the whole board. */
|
||||
hw?: string;
|
||||
title: string;
|
||||
summary: string;
|
||||
/** The options it reads besides the shared ones (SHARED_OPTIONS). */
|
||||
options: string[];
|
||||
}
|
||||
|
||||
/** Read by every shortcode that names program files. */
|
||||
export const SHARED_OPTIONS = ['lingo', 'matho', 'pseudo', 'speco', 'mojo', 'asm', 'setup', 'lang', 'call', 'input', 'machine', 't', 'title', 'caption', 'collapse', 'area'] as const;
|
||||
|
||||
/** Read by every rendered view (the machine's too). */
|
||||
export const RENDERED_OPTIONS = ['code', 'numbers', 'live', 'height', 'column'] as const;
|
||||
|
||||
export const SHORTCODES: ShortcodeDef[] = [
|
||||
{ name: 'pplus-run', kind: 'rendered', view: 'run', title: 'Run it', summary: 'What the program prints and returns, checked against its EXPECT lines. A Mojo file runs on the real compiler when the machine that renders has one.', options: ['compiler'] },
|
||||
{ name: 'pplus-steps', kind: 'rendered', view: 'steps', title: 'Step through it', summary: 'The listing beside a stepper: every step, the line it ran, what it wrote, the values after it, and what was printed so far. The run is in the page; a small script moves through it.', options: ['follow', 'max'] },
|
||||
{ name: 'pplus-table', kind: 'rendered', view: 'table', title: 'Table of values', summary: 'The table you would draw by hand: a column per step that changed something, a row per name.', options: [] },
|
||||
{ name: 'pplus-flow', kind: 'rendered', view: 'flow', title: 'Flowchart', summary: 'The routine as a flowchart, laid out from its structure; each box shaded by how often its line ran, each arrow labeled with how often it was taken.', options: [] },
|
||||
{ name: 'pplus-dataflow', kind: 'rendered', view: 'data', title: 'Data flow', summary: 'Which names feed which: the parameters on the left, what leaves on the right, an arrow for each assignment.', options: [] },
|
||||
{ name: 'pplus-lifetimes', kind: 'rendered', view: 'life', title: 'Lifetimes', summary: 'Each Mojo value from the step it is made to the step it is destroyed or moved out of, with every copy and move on the way.', options: [] },
|
||||
{ name: 'pplus-proof', kind: 'rendered', view: 'proof', title: 'Proof', summary: 'Every claim the specification makes (ENSURE, INVARIANT, a .speco file woven in): proved, broken by a run, or open.', options: [] },
|
||||
{ name: 'pplus-tests', kind: 'rendered', view: 'tests', title: 'Generated tests', summary: 'The fuzzer\'s report for each routine: what each input must do, how the inputs were made, every failure shrunk to the smallest input, every case run.', options: [] },
|
||||
{ name: 'pplus-check', kind: 'rendered', view: 'check', title: 'The checker', summary: 'What Programming+ finds in each file before anything runs, on the file\'s own lines, with a link to the guide.', options: [] },
|
||||
{ name: 'pplus-translate', kind: 'rendered', view: 'translate', title: 'Every notation', summary: 'One file in, the procedure in every notation out: lingo, matho, pseudo, speco, and Mojo generated from the pseudo (and labeled so). As tabs, columns, or the app\'s panes.', options: ['to', 'layout'] },
|
||||
{ name: 'pplus-machine', kind: 'rendered', view: 'machine', title: 'The machine', summary: 'An x86-64 run on the model machine: instructions, cycles on an in-order and an out-of-order core, cache misses, branches, and what bounds it.', options: [] },
|
||||
{ name: 'pplus-view', kind: 'rendered', view: undefined, title: 'Any view by name', summary: 'Any of the rendered views, chosen with view= (run, steps, table, flow, data, life, proof, tests, check, translate, machine).', options: ['view'] },
|
||||
{ name: 'pplus-hw', kind: 'machine', view: 'hw', title: 'The machine board', summary: 'The Hardware area\'s board over an x86-64 run: the listing beside the cards of a preset (registers and memory, caches, pipeline, the whole chip) or the views you name, every one drawn at every step, with a stepper.', options: ['preset', 'views', 'listing', 'stepper', 'max'] },
|
||||
...Object.entries(HW_NAMES).map(([name, id]): ShortcodeDef => {
|
||||
const v = boardView(id)!;
|
||||
return { name: `pplus-hw-${name}`, kind: 'machine', view: 'hw', hw: name, title: v.label, summary: v.blurb, options: ['listing', 'stepper', 'max'] };
|
||||
}),
|
||||
{ name: 'pplus-playground', kind: 'live', view: 'playground', title: 'The whole playground', summary: 'The app in the page: every pane, the stepper, every inspect tab and the dock. The reader\'s edits are kept in their browser; Reset brings the page\'s version back.', options: ['panel', 'build', 'dock', 'docktab', 'editor', 'side', 'dockheight', 'theme', 'ro', 'height', 'problem', 'state'] },
|
||||
{ name: 'pplus-embed', kind: 'live', view: 'any', title: 'One live view', summary: 'One view of the app with the code it reads: trace, table, flow, data, life, problems, proof, tests, compiler, asm, or one pane.', options: ['view', 'panel', 'build', 'theme', 'ro', 'showcall', 'split', 'height', 'problem', 'state'] },
|
||||
{ name: 'pplus', kind: 'live', view: 'any', title: 'The original shortcode', summary: 'A live embed, a listing, or both (show=). Pages written for it keep working.', options: ['view', 'show', 'mode', 'text', 'panel', 'build', 'theme', 'ro', 'showcall', 'split', 'height', 'problem', 'state'] },
|
||||
{ name: 'pplus-listing', kind: 'text', title: 'Listings', summary: 'The files as highlighted code blocks, without their header lines; a .tex file typeset as equations.', options: ['numbers', 'math', 'link', 'text'] },
|
||||
{ name: 'pplus-tabs', kind: 'text', title: 'Tabs', summary: 'The files as a tabset, one tab per notation.', options: ['numbers', 'math'] },
|
||||
{ name: 'pplus-link', kind: 'text', title: 'A link', summary: 'A link that opens the program in the app.', options: ['view', 'text'] },
|
||||
];
|
||||
|
||||
export const SHORTCODE_NAMES: readonly string[] = SHORTCODES.map((s) => s.name);
|
||||
|
||||
export const OPTION_DOCS: Record<string, string> = {
|
||||
lingo: 'a lingo file beside the page', matho: 'a LaTeX (.tex) file of equations', pseudo: 'a pseudo file', speco: 'a speco file (the specification)',
|
||||
mojo: 'a Mojo file', asm: 'an x86-64 listing', setup: 'the x86-64 setup block: registers and memory',
|
||||
lang: 'the pane that runs (default: the first of lingo, matho, pseudo, mojo, asm given)',
|
||||
call: 'the call to run (default: the file\'s // CALL: line)', input: 'lines INPUT reads, separated by |', machine: 'the x86-64 machine model preset',
|
||||
t: 'the step the stepper starts on', title: 'a title over the view', caption: 'a sentence under it', collapse: '1 folds it into a block the reader opens',
|
||||
area: 'bridge, dev or hw: where "open in the playground" goes',
|
||||
code: '1 prints the program above the view', numbers: '1 numbers the listing\'s lines', live: 'click adds "make it live", which puts the live view in its place',
|
||||
height: 'the live frame\'s height in px (auto: fits its content)', compiler: 'auto (the real mojo when on the PATH), on, or off',
|
||||
follow: 'the variables to show, comma-separated', max: 'the most steps kept (default 400; a longer machine run is sampled)', to: 'the notations to show, comma-separated',
|
||||
layout: 'tabs (default), columns, or grid',
|
||||
preset: 'the board\'s arrangement: regs (default), caches, pipeline or chip', views: 'the machine views to show, comma-separated (registers, memory, cache, pipeline, chip...)',
|
||||
listing: '0 leaves out the x86-64 listing', column: 'Quarto\'s column for the figure: body, page (pplus-hw\'s default), screen...', stepper: '0 draws only step t, without a stepper', view: 'which view', panel: 'the tab the playground opens on', build: 'O0 (as written) or default (as mojo build does)',
|
||||
dock: 'open or closed', docktab: 'the dock\'s tab', editor: 'the editor column\'s share of the width', side: 'the variables panel\'s share', dockheight: 'the editors\' share of the height',
|
||||
theme: 'light or dark (default: follow the page)', ro: '1: read-only, nothing saved', showcall: '0 hides the run box', split: 'the code\'s share of the frame',
|
||||
problem: 'a catalog problem instead of files', state: 'a state from the playground\'s Share dialog', show: 'embed, listing or both', mode: 'link: only a link', text: 'the link\'s text', math: '0 prints a .tex file as code', link: '1 adds a link to the app',
|
||||
};
|
||||
|
||||
/** The shortcode as a page writes it. */
|
||||
export function shortcodeText(name: string, attrs: Record<string, string>): string {
|
||||
const parts = Object.entries(attrs).map(([k, v]) => `${k}="${v.replace(/"/g, '"')}"`);
|
||||
return `{{< ${name}${parts.length ? ' ' + parts.join(' ') : ''} >}}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* A title from a state (which anyone can write into a link) as a shortcode argument the Share dialog hands to a page
|
||||
* author: one line, at most 120 characters, a double quote as `"` (pplus.lua reads it back), and none of the
|
||||
* characters that could end the shortcode or start markup in the page it is pasted into (`<`, `>`, `{`, `}`).
|
||||
*/
|
||||
export function shortcodeTitle(title: string): string {
|
||||
return title.replace(/[<>{}]/g, '').replace(/\s+/g, ' ').trim().slice(0, 120).replace(/"/g, '"');
|
||||
}
|
||||
|
||||
const PANES: LangId[] = ['lingo', 'matho', 'pseudo', 'speco', 'mojo', 'asm'];
|
||||
const list = (s: string | undefined) => (s ? s.split(/[\s,]+/).filter(Boolean) : undefined);
|
||||
|
||||
/**
|
||||
* What a rendered shortcode asks render.ts for, given its options and the files beside the page (by name): the
|
||||
* same request pplus.lua builds, for the gallery to draw what a page would get.
|
||||
*/
|
||||
export function requestFor(view: StaticView, attrs: Record<string, string>, files: Record<string, string>): RenderRequest {
|
||||
const req: RenderRequest = { view, files: {} };
|
||||
for (const p of PANES) if (attrs[p] && files[attrs[p]] !== undefined) req.files[p] = files[attrs[p]];
|
||||
if (attrs.lang) req.lang = attrs.lang as LangId;
|
||||
if (attrs.call) req.call = attrs.call;
|
||||
if (attrs.input) req.input = attrs.input.split('|');
|
||||
if (attrs.setup && files[attrs.setup] !== undefined) req.setup = files[attrs.setup];
|
||||
if (attrs.machine) req.machine = attrs.machine;
|
||||
if (attrs.t && Number.isFinite(Number(attrs.t))) req.t = Number(attrs.t);
|
||||
if (attrs.title) req.title = attrs.title;
|
||||
if (attrs.max && Number.isFinite(Number(attrs.max))) req.max = Number(attrs.max);
|
||||
if (attrs.views) req.hw = list(attrs.views);
|
||||
if (attrs.preset) req.preset = attrs.preset;
|
||||
if (attrs.listing === '0') req.listing = false;
|
||||
if (attrs.stepper === '0') req.stepper = false;
|
||||
req.follow = list(attrs.follow);
|
||||
req.to = list(attrs.to) as LangId[] | undefined;
|
||||
return req;
|
||||
}
|
||||
|
||||
/** The state a live shortcode puts in its iframe's URL: the same one pplus.lua writes. */
|
||||
export function liveStateFor(attrs: Record<string, string>, files: Record<string, string>): PlayState {
|
||||
const s = emptyState();
|
||||
let first: LangId | null = null;
|
||||
let call: string | undefined; let input: string[] | undefined;
|
||||
for (const p of PANES) {
|
||||
const text = attrs[p] ? files[attrs[p]] : undefined;
|
||||
if (text === undefined) continue;
|
||||
s.sources[p] = listingText(text, p);
|
||||
first ??= p;
|
||||
for (const line of text.split('\n')) {
|
||||
const m = /^\s*(?:\/\/|%|#)\s*(CALL|INPUT):\s?(.*)$/.exec(line);
|
||||
if (m?.[1] === 'CALL') call ??= m[2].trim();
|
||||
if (m?.[1] === 'INPUT') (input ??= []).push(m[2]);
|
||||
}
|
||||
}
|
||||
s.lang = (attrs.lang as LangId) || first || 'pseudo';
|
||||
s.view = 'trace';
|
||||
if (attrs.setup && files[attrs.setup] !== undefined) s.setup = files[attrs.setup];
|
||||
const c = attrs.call ?? call;
|
||||
if (c) s.call = c;
|
||||
if (attrs.input) s.input = attrs.input.split('|').join('\n'); else if (input) s.input = input.join('\n');
|
||||
if (attrs.title) s.title = attrs.title;
|
||||
if (attrs.t) s.t = Number(attrs.t);
|
||||
return s;
|
||||
}
|
||||
Reference in new issue
Block a user