Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 7 additions & 2 deletions client/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
"name": "liquid-java",
"displayName": "LiquidJava",
"description": "Extending Java with Liquid Types",
"version": "0.1.2",
"version": "0.1.3",
"publisher": "AlcidesFonseca",
"repository": {
"type": "git",
Expand Down Expand Up @@ -70,10 +70,15 @@
"default": true,
"description": "Show the details of an error in the editor hover under its message: the origin notes, the counterexample and the hints. When off, the hover shows the message alone and the details are in the LiquidJava view, where the hints stay closed until opened."
},
"liquidjava.hover.formattedMessage": {
"type": "boolean",
"default": false,
"description": "Under the plain message of an error, show Expected and Found as code in the editor hover. Meant for user studies."
},
"liquidjava.usageLog": {
"type": "string",
"default": "",
"description": "Path of a JSON Lines file to which the extension appends what is used in the LiquidJava view: tabs, hints opened, Found steps, locations, state machine, copies. Empty: nothing is written. Meant for user studies."
"description": "Path of a JSON Lines file to which the extension appends what is used in the LiquidJava view: tabs, hints, origin and locations opened, Found steps, state machine, copies, clicks on an error card. Empty: nothing is written. Meant for user studies."
}
}
},
Expand Down
19 changes: 17 additions & 2 deletions client/src/services/hover.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { getOriginalVariableName, normalizeFilePath } from '../utils/utils';
import { definitionMatchesClass, getDefinitions } from './definition';
import { isExtensionRunning } from '../extension';
import type { SourcePosition } from '../types/diagnostics';
import { formatDiagnosticMarkdown } from '../utils/message-markdown';
import { formatDiagnosticMarkdown, formatPlainMessage } from '../utils/message-markdown';

/**
* Initializes hover provider for LiquidJava diagnostics
Expand All @@ -31,7 +31,8 @@ export function registerHover() {
}
}

const contents = [hoverContent, ...getHoveredDiagnostics(document, position)].filter(content => content.value.length > 0);
const contents = [hoverContent, ...getFormattedMessages(document, position), ...getHoveredDiagnostics(document, position)]
.filter(content => content.value.length > 0);
if (contents.length === 0) return null;
return new vscode.Hover(contents);
}
Expand All @@ -57,6 +58,20 @@ function getHoveredDiagnostics(document: vscode.TextDocument, position: vscode.P
.map(markdown => new vscode.MarkdownString(markdown));
}

/**
* The message of each LiquidJava error at a position, formatted: Expected and Found as inline code on their own
* lines, under the plain line VS Code shows from the Problems entry ("Refinement Error: found A but expected B").
* Only when liquidjava.hover.formattedMessage is on (user studies: the hover reads like the view)
*/
function getFormattedMessages(document: vscode.TextDocument, position: vscode.Position): vscode.MarkdownString[] {
if (!vscode.workspace.getConfiguration().get<boolean>('liquidjava.hover.formattedMessage', false)) return [];
return vscode.languages.getDiagnostics(document.uri)
.filter(diagnostic => diagnostic.source === 'liquidjava' && diagnostic.range.contains(position))
.map(diagnostic => formatPlainMessage(diagnostic.message))
.filter((markdown): markdown is string => markdown !== null)
.map(markdown => new vscode.MarkdownString(markdown));
}

// liquidjava.hover.showDetails: off keeps the origin notes, the counterexample and the hints in the view only (user
// studies). liquidjava.hover.showHints, its name in 0.1.1, still counts when a settings file sets it to false
function showDetailsInHover(): boolean {
Expand Down
28 changes: 22 additions & 6 deletions client/src/services/webview.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,10 @@ import * as vscode from "vscode";
import { LiquidJavaWebviewProvider } from "../webview/provider";
import { extension } from "../state";
import type { DiagnosticRevealTarget } from "../types/diagnostics";
import type { NavTab } from "../webview/views/sections";
import type { FoldKind, NavTab } from "../webview/views/sections";

/** What liquidjava.showView may do besides opening the view: openFolds opens the named folds (hints, origin, locations) */
export type ShowViewOptions = { openFolds?: FoldKind[] };
import { logUsage } from "./usage-log";

/**
Expand All @@ -13,6 +16,12 @@ export function registerWebview(context: vscode.ExtensionContext) {
extension.webview = new LiquidJavaWebviewProvider(context.extensionUri);
let pendingDiagnosticReveal: { diagnostic: DiagnosticRevealTarget, tab?: NavTab } | undefined;
let pendingTab: NavTab | undefined;
let pendingFolds: FoldKind[] | undefined;
const openFolds = (kinds: FoldKind[] | undefined, visible: boolean | undefined) => {
if (!kinds || kinds.length === 0) return;
if (visible) extension.webview?.sendMessage({ type: "openFolds", kinds });
else pendingFolds = kinds;
};

// webview provider
context.subscriptions.push(
Expand All @@ -24,14 +33,16 @@ export function registerWebview(context: vscode.ExtensionContext) {
// shows the diagnostic in the Verification tab, or a state error in the State Machine tab when tab is 'fsm';
// without a diagnostic, opens the tab, if one is given. from names the caller in the usage log: the code
// lenses above an error (the default), or another extension
vscode.commands.registerCommand("liquidjava.showView", async (diagnostic?: DiagnosticRevealTarget, tab?: NavTab, from = 'code-lens') => {
vscode.commands.registerCommand("liquidjava.showView", async (diagnostic?: DiagnosticRevealTarget, tab?: NavTab, from = 'code-lens', options: ShowViewOptions = {}) => {
const isVisible = extension.webview?.isVisible();
await vscode.commands.executeCommand("liquidJavaView.focus");
if (!diagnostic) {
if (!tab) return;
logUsage('tab', { tab, from });
if (isVisible) extension.webview?.sendMessage({ type: "selectTab", tab });
else pendingTab = tab;
if (tab) {
logUsage('tab', { tab, from });
if (isVisible) extension.webview?.sendMessage({ type: "selectTab", tab });
else pendingTab = tab;
}
openFolds(options.openFolds, isVisible);
return;
}
// the code lenses above an error: its title opens the Verification tab, "Show in state machine" the State Machine tab
Expand All @@ -42,6 +53,7 @@ export function registerWebview(context: vscode.ExtensionContext) {
} else {
pendingDiagnosticReveal = { diagnostic, tab };
}
openFolds(options.openFolds, isVisible);
})
);
// listen for messages from the webview
Expand All @@ -61,6 +73,10 @@ export function registerWebview(context: vscode.ExtensionContext) {
extension.webview?.sendMessage({ type: "selectTab", tab: pendingTab });
pendingTab = undefined;
}
if (pendingFolds) {
extension.webview?.sendMessage({ type: "openFolds", kinds: pendingFolds });
pendingFolds = undefined;
}
}
})
);
Expand Down
21 changes: 21 additions & 0 deletions client/src/utils/message-markdown.plain.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { describe, expect, it } from "vitest";
import { formatPlainMessage } from "./message-markdown";

describe("formatPlainMessage", () => {
it("formats found and expected as code, Expected first", () => {
expect(formatPlainMessage("State Refinement Error: found empty(kettle) but expected filled(kettle)"))
.toBe("**Expected** `filled(kettle)`\n\n**Found** `empty(kettle)`");
});
it("keeps a found with a but inside it whole", () => {
expect(formatPlainMessage("Refinement Error: found a > 0 && b == 1 but expected a > 0 && b > 1"))
.toBe("**Expected** `a > 0 && b > 1`\n\n**Found** `a > 0 && b == 1`");
});
it("says what is known when nothing proves the expectation", () => {
expect(formatPlainMessage("Refinement Error: expected timeout >= 0 but could not prove it"))
.toBe("**Expected** `timeout >= 0`\n\n**Found** nothing here that proves it");
});
it("leaves other messages alone", () => {
expect(formatPlainMessage("Refinement Error")).toBeNull();
expect(formatPlainMessage("Java: cannot find symbol")).toBeNull();
});
});
15 changes: 15 additions & 0 deletions client/src/utils/message-markdown.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,3 +72,18 @@ function formatInlineCode(code: string): string {
function escapeMarkdown(text: string): string {
return text.replace(/[!-/:-@[-`{-~]/g, "\\$&");
}

/**
* The plain one-line message of an error, as the Problems entry shows it, formatted for the hover: Expected and Found
* as inline code on their own lines. The two shapes the server writes are "Kind: found A but expected B" and
* "Kind: expected B but could not prove it" (nothing known at that point proves B)
* @returns the markdown, or null for any other text
*/
export function formatPlainMessage(message: string): string | null {
const text = message.trim();
const found = /^[^:]+: found ([\s\S]+) but expected ([\s\S]+)$/.exec(text);
if (found) return `**Expected** ${formatInlineCode(found[2])}\n\n**Found** ${formatInlineCode(found[1])}`;
const unproven = /^[^:]+: expected ([\s\S]+) but could not prove it$/.exec(text);
if (unproven) return `**Expected** ${formatInlineCode(unproven[1])}\n\n**Found** nothing here that proves it`;
return null;
}
32 changes: 32 additions & 0 deletions client/src/webview/script.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -200,6 +200,38 @@ describe('webview script', () => {
]);
});

it('opens the requested folds on the next render when asked while loading (the tour asks for the hints)', () => {
receive({ type: 'openFolds', kinds: ['hints'] }); // the initial view is loading: nothing to open yet
showDiagnostics([{ ...diagnostic(currentFile, 'State error'), hints: [{ kind: 'general', message: 'Call `open()` first' }] }]);
const hints = root.querySelector<HTMLDetailsElement>('details[data-fold-kind="hints"]');
expect(hints!.open, 'the hints open once the diagnostics are rendered').toBe(true);
expect(root.querySelector<HTMLDetailsElement>('details[data-fold-kind="origin"]')?.open ?? false).toBe(false);
expect(postMessage.mock.calls.filter(([m]) => (m as { action?: string }).action === 'hints')).toEqual([]);

// the request is spent: another error's hints render closed
const another = diagnostic(currentFile, 'Another error');
another.position = { ...another.position, lineStart: another.position.lineStart + 5, lineEnd: another.position.lineEnd + 5 };
showDiagnostics([{ ...another, hints: [{ kind: 'general', message: 'Call `close()` first' }] }]);
expect(root.querySelector<HTMLDetailsElement>('details[data-fold-kind="hints"]')!.open).toBe(false);
});

it('shows the error in the code on a click on its card, except after a text selection', () => {
showDiagnostics([diagnostic(currentFile, 'State error')]);
postMessage.mockClear();
const card = root.querySelector<HTMLElement>('.error-item');
expect(card).not.toBeNull();
const text = card!.querySelector<HTMLElement>('h3') ?? card!;

dom.window.getSelection()!.selectAllChildren(text); // a drag over the message, then its click
text.click();
expect(postMessage.mock.calls.filter(([m]) => (m as { type: string }).type === 'openFile')).toEqual([]);

dom.window.getSelection()!.removeAllRanges();
text.click();
expect(postMessage.mock.calls).toContainEqual([{ type: 'usage', action: 'reveal-code', file: currentFile, line: position.lineStart + 1 }]);
expect(postMessage.mock.calls.filter(([m]) => (m as { type: string }).type === 'openFile')).toHaveLength(1);
});

it('opens a tab on a selectTab message (the liquidjava.showView command with a tab and no diagnostic)', () => {
showDiagnostics([diagnostic(currentFile, 'Current error')]);
receive({ type: 'fsm', sms: [stateMachine] });
Expand Down
55 changes: 45 additions & 10 deletions client/src/webview/script.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import type { LJDiagnostic, RefinementMismatchError, StateRefinementError } from
import type { Range } from "../types/context";
import type { LJStateMachine } from "../types/fsm";
import type { ExtensionStatus } from "../state";
import { setHintOpen, type NavTab } from "./views/sections";
import { setFoldOpen, type FoldKind, type NavTab } from "./views/sections";
import { copyDiagnosticToClipboard, getCurrentFileErrorCount, getDisplayDiagnostics, renderDiagnosticsView } from "./views/diagnostics/diagnostics";
import type { LJContext } from "../types/context";
import { ContextSectionState, renderContextView } from "./views/context/context";
Expand Down Expand Up @@ -62,21 +62,39 @@ export function getScript(vscode: VSCodeApi, document: Document, window: Window)

// on click
// toggle does not bubble, so it is caught on its way down. A render of an open <details> fires it too, so only a
// toggle right after the summary was clicked or keyed counts as the user opening or closing the hints
let hintToggleByUser = false;
const markHintToggle = (e: Event) => { if ((e.target as Element).closest?.('.hint-summary')) hintToggleByUser = true; };
root.addEventListener('click', markHintToggle, true);
root.addEventListener('keydown', markHintToggle, true);
// toggle right after the summary was clicked or keyed counts as the user opening or closing a fold (hints, origin,
// locations); the usage event carries the fold's kind
let foldToggleByUser = false;
const markFoldToggle = (e: Event) => { if ((e.target as Element).closest?.('.hint-summary, .fold-summary')) foldToggleByUser = true; };
root.addEventListener('click', markFoldToggle, true);
root.addEventListener('keydown', markFoldToggle, true);
root.addEventListener('toggle', (e: Event) => {
const details = e.target as HTMLDetailsElement;
const key = details.getAttribute?.('data-hint-key');
const key = details.getAttribute?.('data-fold-key');
const kind = (details.getAttribute?.('data-fold-kind') ?? 'hints') as FoldKind;
if (key !== null && key !== undefined) {
setHintOpen(key, details.open);
if (hintToggleByUser) usage('hints', { open: details.open, error: key });
setFoldOpen(kind, key, details.open);
if (foldToggleByUser) usage(kind, { open: details.open, error: key });
}
hintToggleByUser = false;
foldToggleByUser = false;
}, true);

// opens every fold of the given kinds in the current render, without counting as a use (the tour does this). A
// request made while the view is loading, or before any diagnostics arrived, waits for the next render that has them.
// A request that finds no such folds in that render is dropped: it must never open a later error's folds unasked
let requestedFolds: FoldKind[] | undefined;
const openFolds = (kinds: FoldKind[]) => {
if (status === 'loading' || !diagnostics) { requestedFolds = kinds; return; }
requestedFolds = undefined;
for (const details of Array.from(root.querySelectorAll<HTMLDetailsElement>('details[data-fold-kind]'))) {
const kind = details.getAttribute('data-fold-kind') as FoldKind;
const key = details.getAttribute('data-fold-key');
if (!kinds.includes(kind) || key === null) continue;
setFoldOpen(kind, key, true);
details.open = true;
}
};

root.addEventListener('click', (e: MouseEvent) => {
const target = e.target instanceof Element ? e.target : null;
if (!target) return;
Expand Down Expand Up @@ -344,6 +362,19 @@ export function getScript(vscode: VSCodeApi, document: Document, window: Window)
copyDiagnosticToClipboard(diagnosticCopyBtn, getDisplayDiagnostics(diagnostics || [], showAllDiagnostics, currentFile));
return;
}

// a click on the card of an error, outside its buttons, links and folds, shows the error in the code. A drag that
// selects text in the card ends with a click too: that one keeps the selection and does not open the file
const errorItem = target.closest?.('.error-item');
if (errorItem && !target.closest('button, a, details')) {
if (window.getSelection?.()?.isCollapsed === false) return;
const revealTarget = getDiagnosticRevealTargetFromKey(errorItem.getAttribute('data-diagnostic-target'));
if (!revealTarget) return;
usage('reveal-code', { file: revealTarget.file, line: revealTarget.position.lineStart + 1 });
const { lineStart, colStart } = revealTarget.position;
vscode.postMessage({ type: 'openFile', filePath: revealTarget.file, line: lineStart, character: colStart, highlightRange: revealTarget.position });
return;
}
});

// navigate context variables with the keyboard
Expand Down Expand Up @@ -426,6 +457,9 @@ export function getScript(vscode: VSCodeApi, document: Document, window: Window)
if (tab !== selectedTab) { selectedTab = tab; updateView(); }
break;
}
case 'openFolds': // the liquidjava.showView command with openFolds in its options
openFolds(msg.kinds as FoldKind[]);
break;
case 'revealDiagnostic': {
const revealTarget = msg.diagnostic as DiagnosticRevealTarget;
const stateError = msg.tab === 'fsm' ? findStateErrorAt(revealTarget) : undefined;
Expand Down Expand Up @@ -459,6 +493,7 @@ export function getScript(vscode: VSCodeApi, document: Document, window: Window)
root.innerHTML = diagnostics
? renderDiagnosticsView(diagnostics, showAllDiagnostics, currentFile, badges)
: renderLoading();
if (requestedFolds && diagnostics) openFolds(requestedFolds);
break;
case 'fsm': {
const { error: shownError, index: shownIndex } = getShownStateError(stateErrors);
Expand Down
7 changes: 5 additions & 2 deletions client/src/webview/styles.ts
Original file line number Diff line number Diff line change
Expand Up @@ -221,13 +221,16 @@ export function getStyles(): string {
gap: 0.25rem;
margin-left: auto;
}
.hint-summary {
.hint-summary, .fold-summary {
font-weight: bold;
cursor: pointer;
}
.hint-section[open] .hint-summary {
.hint-section[open] .hint-summary, .fold-section[open] .fold-summary {
margin-bottom: 0.25rem;
}
.fold-body .message-note {
margin: 0;
}
.hint-body {
padding: 0.5rem;
background-color: var(--vscode-editor-background);
Expand Down
6 changes: 5 additions & 1 deletion client/src/webview/views/diagnostics/diagnostics.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,11 @@ describe('diagnostics view', () => {
const link = document.querySelector('.message-note a.location-link');
expect(link?.textContent).toBe('line 134');
expect([link?.getAttribute('data-file'), link?.getAttribute('data-line')]).toEqual(['/workspace/Reader.java', '133']);
expect(text('.message-note')).toBe('Origin: line 134, new BufferedInputStream(stream) makes markState(b) == unmarked');
// the note sits in a fold titled Origin, closed until opened, so its own "Origin:" prefix is not repeated
expect(text('.message-note')).toBe('line 134, new BufferedInputStream(stream) makes markState(b) == unmarked');
const origin = document.querySelector<HTMLDetailsElement>('details.fold-origin');
expect(origin?.open).toBe(false);
expect(origin?.querySelector('summary')?.textContent).toBe('Origin');
expect(Array.from(document.querySelectorAll('.lj-code')).map(code => code.textContent))
.toEqual(['new BufferedInputStream(stream)', 'markState(b) == unmarked', "b.f('`')", 'sl9 = "x@1"']);
expect(document.querySelector('.lj-code sub.lj-line-tag')?.getAttribute('title')).toBe('s at line 9');
Expand Down
Loading
Loading