diff --git a/src/common/baseplatform.ts b/src/common/baseplatform.ts index df62c8fc..e29151ba 100644 --- a/src/common/baseplatform.ts +++ b/src/common/baseplatform.ts @@ -17,7 +17,7 @@ import { _MOS6502 } from "./cpu/MOS6502"; import { AcceptsBIOS, AcceptsJoyInput, AcceptsKeyInput, AcceptsPaddleInput, AcceptsROM, Bus, FrameBased, HasCPU, HasSerialIO, Probeable, RasterFrameBased, Resettable, SampledAudioSource, SavesInputState, SavesState, SerialIOInterface, VideoSource } from "./devices"; import { ProbeRecorder } from "./probe"; import { BaseWASMMachine } from "./wasmplatform"; -import { formatSourceVariableLine, globalVariablesOf, globalVariableTree, liveSourceVariables, readSourceByte, sourceVariablesOf, sourceVariableTree, writableGlobalVariablesOf } from "./sourcevars"; +import { formatSourceVariableLine, globalVariablesOf, inlineSourceValues, LineOffset, globalVariableTree, liveSourceVariables, readSourceByte, sourceVariablesOf, sourceVariableTree, writableGlobalVariablesOf } from "./sourcevars"; /// @@ -435,6 +435,15 @@ export abstract class BaseDebugPlatform extends BasePlatform { this.debugSymbols.symbolsizes, a => readSourceByte(this, a)) || {}; } + /** The live source variables to draw at the end of the lines that name + * them, keyed by 1-based line number; empty without variable info. */ + getInlineSourceValues(lines: LineOffset[], lineText: (line: number) => string | null, stopLine?: number | null): Map { + const vars = sourceVariablesOf(this.debugSymbols?.debuginfo); + if (!vars.length) return new Map(); + return inlineSourceValues(vars, this.debugPC(), this.debugSymbols.symbolmap, + this.debugSymbols.symbolsizes, lines, lineText, a => readSourceByte(this, a), stopLine); + } + /** The writable source-declared globals (`static`, `reg!`) and their * values, keyed `name:type`; constants in ROM are left out. */ getGlobalVariables(): { [name: string]: any } { diff --git a/src/common/sourcevars.ts b/src/common/sourcevars.ts index e4d0ce0b..f03e8397 100644 --- a/src/common/sourcevars.ts +++ b/src/common/sourcevars.ts @@ -261,3 +261,83 @@ export function globalVariableTree(vars: GlobalVariable[], read: (addr: number) => number): { [name: string]: any } | null { return vars.length ? variablesToTree(vars, read) : null; } + +/** A source line and the address where its code starts (one entry per listed line). */ +export interface LineOffset { line: number; offset: number } + +/** + * The code range of each source line: from its first listed address to the + * next listed address after it. Compilers list a line once per code run, so + * a line can have several ranges. + */ +export function lineCodeRanges(lines: LineOffset[]): Map { + const sorted = lines.filter(l => l.offset >= 0).sort((a, b) => a.offset - b.offset); + const out = new Map(); + for (let i = 0; i < sorted.length; i++) { + let j = i + 1; + while (j < sorted.length && sorted[j].offset === sorted[i].offset) j++; + const end = j < sorted.length ? sorted[j].offset : sorted[i].offset + 1; + const list = out.get(sorted[i].line) || []; + list.push([sorted[i].offset, end]); + out.set(sorted[i].line, list); + } + return out; +} + +function overlaps(a: [number, number], b: [number, number]): boolean { + return a[0] < b[1] && b[0] < a[1]; +} + +/** Does `name` appear in `text` as a whole identifier? */ +function mentions(text: string, name: string): boolean { + const re = new RegExp(`(^|[^A-Za-z0-9_])${name.replace(/[^A-Za-z0-9_]/g, '\\$&')}($|[^A-Za-z0-9_])`); + return re.test(text); +} + +/** + * The variables to show at the end of source lines while stopped at `pc`, as + * `name = value` text keyed by 1-based line number. + * + * A variable is a candidate on a line when it is live at `pc` (so its home + * holds its value now), the line's own code lies in its live range (or the + * line has no known code), and the line's text names it. The live range + * alone would list nearly every variable on every line of a function; the + * name test keeps it to the lines that touch a variable. + * + * Each variable is then shown once, on its candidate line nearest `stopLine` + * (ties go to the earlier line), so a loop index is not repeated on every + * line that uses it. Without a `stopLine` the first candidate wins. + */ +export function inlineSourceValues(vars: SourceVariable[], pc: number, + symbolmap: { [name: string]: number }, symbolsizes: { [name: string]: number } | undefined, + lines: LineOffset[], lineText: (line: number) => string | null, + read: (addr: number) => number, stopLine?: number | null): Map { + const live = liveSourceVariables(vars, pc, symbolmap, symbolsizes); + const result = new Map(); + if (!live.length) return result; + const codeRanges = lineCodeRanges(lines); + const candidates = [...new Set([...codeRanges.keys(), ...live.map(v => v.line || 0)])] + .filter(l => l > 0).sort((a, b) => a - b); + const distance = (l: number) => stopLine == null ? 0 : Math.abs(l - stopLine); + const parts = new Map(); + for (const v of live) { + const val = formatSourceValue(v, read); + // a long array is the Locals tree's job, not a line's + if (typeof val !== 'string') continue; + const vr: [number, number][] = v.ranges && v.ranges.length ? v.ranges : v.range ? [v.range] : []; + let best = -1; + for (const line of candidates) { + const text = lineText(line); + if (!text || !mentions(text, v.name)) continue; + const ranges = codeRanges.get(line); + if (ranges && vr.length && !ranges.some(r => vr.some(x => overlaps(r, x)))) continue; + if (best < 0 || distance(line) < distance(best)) best = line; + } + if (best < 0) continue; + const list = parts.get(best) || []; + list.push(`${v.name} = ${val.replace(/^\$[0-9a-f]+ \((-?\d+)\)$/i, '$1')}`); + parts.set(best, list); + } + for (const [line, list] of parts) result.set(line, list.join(', ')); + return result; +} diff --git a/src/ide/views/debugline.ts b/src/ide/views/debugline.ts index 66d64d8e..2df9796c 100644 --- a/src/ide/views/debugline.ts +++ b/src/ide/views/debugline.ts @@ -2,12 +2,48 @@ // current-line (PC) marker and the breakpoint markers. Shared by SourceEditor // and HeaderView (urust rs8 modules), so the two can't drift apart. -import { EditorView } from "@codemirror/view"; +import { StateEffect, StateField } from "@codemirror/state"; +import { Decoration, DecorationSet, EditorView, WidgetType } from "@codemirror/view"; import { SourceLocation } from "../../common/workertypes"; import { bpStore } from "../breakpoints"; import { breakpointMarkers, currentPcMarker, errorMarkers, statusMarkers } from "./gutter"; import { currentPc } from "./visuals"; +// Variable values drawn at the end of the source lines that name them, while +// the program is stopped. Replaced wholesale on every stop; cleared on run. +const setInlineValues = StateEffect.define>(); + +class InlineValueWidget extends WidgetType { + constructor(readonly text: string) { super(); } + eq(o: InlineValueWidget) { return o.text === this.text; } + toDOM() { + const el = document.createElement("span"); + el.className = "cm-inline-value"; + el.textContent = this.text; + return el; + } + ignoreEvent() { return true; } +} + +export const inlineValuesField = StateField.define({ + create() { return Decoration.none; }, + update(deco, tr) { + deco = deco.map(tr.changes); + for (const e of tr.effects) { + if (!e.is(setInlineValues)) continue; + const doc = tr.state.doc; + const ranges = []; + for (const [line, text] of [...e.value].sort((a, b) => a[0] - b[0])) { + if (line < 1 || line > doc.lines) continue; + ranges.push(Decoration.widget({ widget: new InlineValueWidget(text), side: 1 }).range(doc.line(line).to)); + } + deco = Decoration.set(ranges); + } + return deco; + }, + provide: f => EditorView.decorations.from(f), +}); + /** Fields and gutters for breakpoints and the current PC line. The status * gutter reads the error field too, so it comes along even in views that * never show errors. Gutter order is the order here: put it after the @@ -19,6 +55,14 @@ export const debugGutterExtensions = [ statusMarkers.gutter, currentPcMarker.field, currentPcMarker.gutter, + inlineValuesField, + EditorView.baseTheme({ + ".cm-inline-value": { + marginLeft: "2em", padding: "0 0.4em", borderRadius: "3px", + color: "#8ec6a0", background: "rgba(142, 198, 160, 0.12)", + fontStyle: "italic", fontSize: "90%", pointerEvents: "none", userSelect: "none", + }, + }), ]; /** Mark `line` (which must be inside the document) as where the CPU is. @@ -47,3 +91,9 @@ export function syncBreakpointMarkers(view: EditorView, path: string) { .map(bp => ({ line: bp.line, enabled: bp.enabled })); view.dispatch({ effects: breakpointMarkers.setAll.of(markers) }); } + +/** Show `values` (line number to `name = value` text) at the end of their + * lines; an empty map removes them. */ +export function showInlineValues(view: EditorView, values: Map) { + view.dispatch({ effects: setInlineValues.of(values) }); +} diff --git a/src/ide/views/editors.ts b/src/ide/views/editors.ts index 721b4e50..4433c137 100644 --- a/src/ide/views/editors.ts +++ b/src/ide/views/editors.ts @@ -31,7 +31,7 @@ import { createIncludeLinkPlugin } from "./includedecorations"; import { isMobileDevice, ProjectView } from "./baseviews"; import { Shortcut } from "../shortcutbar"; import { createTextTransformFilterEffect, textTransformFilterCompartment } from "./filters"; -import { debugGutterExtensions, clearDebugLine, showDebugLine, syncBreakpointMarkers } from "./debugline"; +import { debugGutterExtensions, clearDebugLine, showDebugLine, showInlineValues, syncBreakpointMarkers } from "./debugline"; import { breakpointMarkers, bytes, clock, currentPcMarker, errorMarkers, ErrorInfo, offset, statusMarkers } from "./gutter"; import { currentPc, errorMessages, errorSpans, highlightLines, showValue, tracedLines } from "./visuals"; import { computeHeatLevels } from "./traceheat"; @@ -643,9 +643,22 @@ export class SourceEditor implements ProjectView { } showDebugLine(this.editor, line, moveCursor); this.currentDebugLine = line; + this.refreshInlineValues(); } } + /** Draw the stopped function's variable values at the ends of the lines + * that name them. Only a halted program has values worth showing. */ + refreshInlineValues() { + const p = platform as any; + if (!this.sourcefile || typeof p.getInlineSourceValues !== "function" || platform.isRunning()) return; + const doc = this.editor.state.doc; + const values = p.getInlineSourceValues(this.sourcefile.lines, + (n: number) => (n >= 1 && n <= doc.lines ? doc.line(n).text : null), + this.currentDebugLine && this.currentDebugLine.line); + showInlineValues(this.editor, values); + } + clearCurrentLine(moveCursor: boolean) { if (this.currentDebugLine) { if (moveCursor) { @@ -655,6 +668,7 @@ export class SourceEditor implements ProjectView { this.currentDebugLine = null; } clearDebugLine(this.editor); + showInlineValues(this.editor, new Map()); } getActiveLine(): SourceLocation { diff --git a/test/unit/testoscar64.ts b/test/unit/testoscar64.ts index 10f7c257..530502ea 100644 --- a/test/unit/testoscar64.ts +++ b/test/unit/testoscar64.ts @@ -1,7 +1,7 @@ import assert from "assert"; import { describe, it } from "mocha"; import { - formatSourceValue, liveSourceVariables, sourceVariableAddress, sourceVariableTree, sourceVariablesOf + formatSourceValue, inlineSourceValues, liveSourceVariables, sourceVariableAddress, sourceVariableTree, sourceVariablesOf } from "../../src/common/sourcevars"; import { parseOscar64Dbj } from "../../src/worker/tools/oscar64parse"; @@ -88,4 +88,22 @@ describe('Oscar64 debug info', function () { assert.strictEqual(tree['i:u8'], '$34 (52)'); assert.strictEqual(tree['score:i16'], '$0000 (0)'); }); + + it('draws each live variable once, near the stop line', function () { + const text: { [line: number]: string } = { + 1: 'int main(int n) {', 10: ' int score = n * 2;', 12: ' for (byte i = 0; i < 4; i++)', + 14: ' score += arr[i];', 18: ' return score;', + }; + const lines = dbj.functions[0].lines.map(l => ({ line: l.line, offset: l.start })); + const mem: { [addr: number]: number } = { 0x9002: 0x34, 0x9003: 0x12, 0x0d: 3 }; + const read = (addr: number) => addr == 0x24 ? 0x90 : mem[addr] || 0; + const m = inlineSourceValues(vars, 0x8005, { main: 0x8000 }, { main: 0x20 }, lines, + l => text[l] ?? null, read, 12); + assert.strictEqual(m.get(12), 'i = 52'); + // `score` and `n` are named on 10, 14 and 18; 10 and 14 are both two + // lines from the stop, so the earlier one wins and neither is repeated + assert.strictEqual(m.get(10), 'score = 0, n = 3'); + assert.strictEqual(m.has(1), false); + assert.strictEqual(m.get(14), 'arr = 00 00 34 12'); + }); }); diff --git a/test/unit/testsourcevars.ts b/test/unit/testsourcevars.ts index 57b39253..bceb8c88 100644 --- a/test/unit/testsourcevars.ts +++ b/test/unit/testsourcevars.ts @@ -2,7 +2,7 @@ import assert from "assert"; import { describe, it } from "mocha"; import { GlobalVariable, SourceVariable, formatSourceValue, formatSourceVariableLine, functionAtPC, - globalVariablesOf, globalVariableTree, liveSourceVariables, sourceVariableTree, sourceVariablesOf, + globalVariablesOf, globalVariableTree, inlineSourceValues, liveSourceVariables, sourceVariableTree, sourceVariablesOf, writableGlobalVariablesOf } from "../../src/common/sourcevars"; @@ -105,3 +105,42 @@ describe('Source variables', function () { assert.strictEqual(formatSourceVariableLine(globals[0], read), 'SCORE: u16 = $5678 (22136)'); }); }); + +describe('Inline source values', function () { + const mem: { [addr: number]: number } = { 0x10: 5, 0x11: 7 }; + const read = (a: number) => mem[a] || 0; + const symbolmap = { main: 0x8000 }; + const symbolsizes = { main: 0x20 }; + const vars: SourceVariable[] = [ + { name: 'i', type: 'u8', size: 1, function: 'main', addr: 0x10, range: [0x8000, 0x8020], line: 2 }, + { name: 'sum', type: 'u8', size: 1, function: 'main', addr: 0x11, range: [0x8008, 0x8020], line: 3 }, + ]; + const text = ['fn main() {', ' let mut i = 0;', ' let mut sum = 0;', ' sum += i;', ' i += 1;']; + const lines = [ + { line: 1, offset: 0x8000 }, { line: 2, offset: 0x8002 }, { line: 3, offset: 0x8008 }, + { line: 4, offset: 0x8010 }, { line: 5, offset: 0x8018 }, + ]; + const run = (stop?: number) => inlineSourceValues(vars, 0x8010, symbolmap, symbolsizes, lines, l => text[l - 1], read, stop); + + it('shows the variables a line names, with their values', function () { + const m = run(4); + assert.strictEqual(m.get(4), 'i = 5, sum = 7'); + }); + it('shows each variable once, on the line nearest the stop', function () { + const m = run(5); + assert.strictEqual(m.get(5), 'i = 5'); + assert.strictEqual(m.get(4), 'sum = 7'); + assert.strictEqual([...m.values()].join().split('i = ').length, 2); + }); + it('skips a variable outside its live range and a line that does not name it', function () { + const m = run(2); + assert.strictEqual(m.get(2), 'i = 5'); // `sum` is not live until line 3's code + assert.strictEqual(m.has(3), true); + assert.strictEqual(m.has(1), false); + }); + it('matches whole identifiers only', function () { + const t = text.slice(); t[4] = ' idx += 1;'; + const m = inlineSourceValues(vars, 0x8010, symbolmap, symbolsizes, lines, l => t[l - 1], read, 5); + assert.strictEqual(m.has(5), false); + }); +});