Files
lucisv/editors/vscode/commentKeywords_test.js
Guoliang ChenandClaude Mythos 5.2 948f8a0b32
release / build-and-publish (push) Successful in 5m28s
Release 0.65.3: comment keywords, and the brackets in comments explained
TODO §71.8. TODO, FIXME, FIX_ME and TBD inside // and /* */ comments are
drawn bold in a new theme colour (lucisv.commentKeyword), as whole words and
never in strings or code; lucisv.commentKeywords.custom adds the user's own
words, .builtIn switches the four off, .caseSensitive ignores case, all live.
Client-side editor decorations: commentScan.js finds comments with the
grammar's own comment and string rules (0 mismatched lines against
vscode-textmate over OpenTitan hw's 1 185 823 lines), commentKeywords.js
matches literally over the visible lines only, with the block-comment state
cached per document.

The brackets sometimes coloured inside comments are VS Code's bracket-pair
colourisation before background tokenization completes, not lucisv (grammar
and semantic tokens measured clean); explained in the notes, not changed.

Dev, QA (pass with findings, one fix round) and lead review are in
docs/features/comment-highlighting/README.md. Not seen in a running editor.

Version bump (Cargo.toml, Cargo.lock, editors/vscode/package.json and both
package-lock.json spots); notes in CHANGELOG.md (## 0.65.3) and
editors/vscode/CHANGELOG.md.

Gates: tools/gates.sh PASS on this tree (20261119-050504), node 37/0.

Co-Authored-By: Claude Mythos 5.2 <[email protected]>
2026-11-19 05:06:35 -08:00

298 lines
12 KiB
JavaScript

// commentKeywords.js against a fake `vscode`: it paints only Verilog editors,
// only around the visible lines, honours every setting change at once, and
// re-reads block-comment state below an edit. Plus the shipped colour's
// contrast against the built-in editor backgrounds
// (docs/features/comment-highlighting).
//
// node --test commentKeywords_test.js
const assert = require('assert/strict');
const fs = require('fs');
const path = require('path');
const test = require('node:test');
const { CommentKeywords, paddedLines, COLOR_ID } = require('./commentKeywords');
/** A fake of the slice of `vscode` the module uses. */
function fakeVscode(settings = {}) {
const handlers = {};
const on = (name) => (handler) => {
handlers[name] = handler;
return { dispose() {} };
};
const vscode = {
settings,
handlers,
decorationOptions: undefined,
Range: class {
constructor(l1, c1, l2, c2) {
Object.assign(this, { l1, c1, l2, c2 });
}
},
ThemeColor: class {
constructor(id) {
this.id = id;
}
},
window: {
visibleTextEditors: [],
createTextEditorDecorationType(options) {
vscode.decorationOptions = options;
return { dispose() {} };
},
onDidChangeVisibleTextEditors: on('visible'),
onDidChangeTextEditorVisibleRanges: on('ranges'),
},
workspace: {
// A language-scoped value (`"[systemverilog]": {...}`, keyed here as
// `[systemverilog]editor.x`) wins when a document is the scope.
getConfiguration(section, scope) {
return {
get: (key, fallback) => {
const scoped = scope && settings[`[${scope.languageId}]${section}.${key}`];
const value = scoped !== undefined ? scoped : settings[`${section}.${key}`];
return value === undefined ? fallback : value;
},
};
},
onDidChangeTextDocument: on('edit'),
onDidOpenTextDocument: on('open'),
onDidCloseTextDocument: on('close'),
onDidChangeConfiguration: on('config'),
},
};
return vscode;
}
function fakeEditor(lines, { languageId = 'systemverilog', visible = [[0, lines.length - 1]] } = {}) {
const document = {
languageId,
lines,
get lineCount() {
return this.lines.length;
},
lineAt(line) {
const text = this.lines[line];
return { text, range: { end: { line, character: text.length } } };
},
offsetAt({ line, character }) {
return this.lines.slice(0, line).reduce((sum, text) => sum + text.length + 1, 0) + character;
},
};
return {
document,
visibleRanges: visible.map(([from, to]) => ({ start: { line: from }, end: { line: to } })),
painted: undefined,
setDecorations(_type, ranges) {
this.painted = ranges.map((r) => `${r.l1}:${document.lines[r.l1].slice(r.c1, r.c2)}`);
},
};
}
const isVerilog = (document) => ['verilog', 'systemverilog'].includes(document.languageId);
function start(vscode, editors, log) {
vscode.window.visibleTextEditors = editors;
const subscriptions = [];
const keywords = new CommentKeywords(vscode, isVerilog, log);
keywords.activate(subscriptions);
return { keywords, subscriptions };
}
function configChange(vscode, ...sections) {
vscode.handlers.config({ affectsConfiguration: (s) => sections.includes(s) });
}
test('paints the built-ins bold in the contributed colour, in Verilog editors only', () => {
const vscode = fakeVscode();
const sv = fakeEditor(['wire TODO; // TODO and TBD']);
const other = fakeEditor(['// TODO'], { languageId: 'plaintext' });
const { subscriptions } = start(vscode, [sv, other]);
assert.deepEqual(sv.painted, ['0:TODO', '0:TBD']);
assert.equal(other.painted, undefined);
assert.equal(vscode.decorationOptions.color.id, COLOR_ID);
assert.equal(vscode.decorationOptions.fontWeight, 'bold');
assert.ok(subscriptions.length >= 7, 'the decoration type and every listener are disposed with the extension');
});
test('only the lines around the visible range are read', () => {
const vscode = fakeVscode();
const lines = Array.from({ length: 1000 }, (_, i) => `// TODO ${i}`);
const editor = fakeEditor(lines, { visible: [[500, 520]] });
let reads = 0;
const lineAt = editor.document.lineAt.bind(editor.document);
editor.document.lineAt = (line) => {
reads += 1;
return lineAt(line);
};
start(vscode, [editor]);
assert.equal(editor.painted.length, 121, 'lines 450..570');
assert.equal(editor.painted[0], '450:TODO');
// The last line once (the size check), lines 0..449 once for the
// block-comment state above the window, then each window line once: its
// scan also gives the next line's state.
assert.equal(reads, 1 + 450 + 121);
reads = 0;
vscode.handlers.ranges({ textEditor: editor });
assert.equal(reads, 121, 'a repaint reuses the states above the window');
});
test('setting changes take effect immediately, both ways', () => {
const vscode = fakeVscode();
const editor = fakeEditor(['// TODO XXX todo hack']);
start(vscode, [editor]);
assert.deepEqual(editor.painted, ['0:TODO']);
vscode.settings['lucisv.commentKeywords.custom'] = ['XXX', 'hack'];
configChange(vscode, 'lucisv.commentKeywords');
assert.deepEqual(editor.painted, ['0:TODO', '0:XXX', '0:hack']);
vscode.settings['lucisv.commentKeywords.builtIn'] = false;
configChange(vscode, 'lucisv.commentKeywords');
assert.deepEqual(editor.painted, ['0:XXX', '0:hack']);
vscode.settings['lucisv.commentKeywords.caseSensitive'] = false;
vscode.settings['lucisv.commentKeywords.builtIn'] = true;
configChange(vscode, 'lucisv.commentKeywords');
assert.deepEqual(editor.painted, ['0:TODO', '0:XXX', '0:todo', '0:hack']);
vscode.settings['lucisv.commentKeywords.builtIn'] = false;
vscode.settings['lucisv.commentKeywords.custom'] = [];
configChange(vscode, 'lucisv.commentKeywords');
assert.deepEqual(editor.painted, [], 'nothing left to highlight clears the decorations');
editor.painted = 'untouched';
configChange(vscode, 'lucisv.rainbowBeginEnd');
assert.equal(editor.painted, 'untouched', 'an unrelated setting repaints nothing');
});
test('unusable custom words are skipped with one line in the output channel', () => {
const vscode = fakeVscode({ 'lucisv.commentKeywords.custom': ['ok', 'two words', ''] });
const logged = [];
const editor = fakeEditor(['// ok']);
start(vscode, [editor], (line) => logged.push(line));
assert.deepEqual(editor.painted, ['0:ok']);
assert.equal(logged.length, 1);
assert.match(logged[0], /ignored 2 entries/);
});
test('an edit above re-reads the block-comment state below it', async () => {
const vscode = fakeVscode();
const editor = fakeEditor(['wire a;', 'TODO', '*/ // TBD']);
start(vscode, [editor]);
assert.deepEqual(editor.painted, ['2:TBD']);
editor.document.lines[0] = 'wire a; /*';
vscode.handlers.edit({ document: editor.document, contentChanges: [{ range: { start: { line: 0 } } }] });
await new Promise((resolve) => setTimeout(resolve, 150));
assert.deepEqual(editor.painted, ['1:TODO', '2:TBD']);
});
test('maxTokenizationLineLength is honoured, and a change to it drops the cached states', () => {
const vscode = fakeVscode({ 'editor.maxTokenizationLineLength': 20 });
const editor = fakeEditor(['/* open', `${'x'.repeat(30)} */`, 'TODO */']);
start(vscode, [editor]);
assert.deepEqual(editor.painted, ['2:TODO'], 'the long line is not tokenized, so the block stays open');
vscode.settings['editor.maxTokenizationLineLength'] = 1000;
configChange(vscode, 'editor.maxTokenizationLineLength');
assert.deepEqual(editor.painted, []);
});
test('a [systemverilog] maxTokenizationLineLength override is the one honoured', () => {
const vscode = fakeVscode({
'editor.maxTokenizationLineLength': 20000,
'[systemverilog]editor.maxTokenizationLineLength': 20,
});
const lines = ['/* open', `${'x'.repeat(30)} */ // TODO`, 'TODO */'];
const sv = fakeEditor(lines);
const v = fakeEditor([...lines], { languageId: 'verilog' });
start(vscode, [sv, v]);
assert.deepEqual(sv.painted, ['2:TODO'], 'the override applies to the systemverilog document');
assert.deepEqual(v.painted, ['1:TODO'], 'and not to the verilog one');
delete vscode.settings['[systemverilog]editor.maxTokenizationLineLength'];
configChange(vscode, 'editor.maxTokenizationLineLength');
assert.deepEqual(sv.painted, ['1:TODO'], 'dropping the override recomputes the states');
});
test('a language-mode change clears or paints at once', async () => {
const vscode = fakeVscode();
const editor = fakeEditor(['// TODO']);
start(vscode, [editor]);
assert.deepEqual(editor.painted, ['0:TODO']);
// What `setTextDocumentLanguage` reports: close, then open, of the document.
const change = async (languageId) => {
vscode.handlers.close(editor.document);
editor.document.languageId = languageId;
vscode.handlers.open(editor.document);
await new Promise((resolve) => setTimeout(resolve, 5));
};
await change('plaintext');
assert.deepEqual(editor.painted, [], 'no longer Verilog: the decorations go');
await change('systemverilog');
assert.deepEqual(editor.painted, ['0:TODO'], 'Verilog again: painted without a scroll or edit');
const foreign = fakeEditor(['// TODO'], { languageId: 'markdown' });
vscode.window.visibleTextEditors.push(foreign);
vscode.handlers.visible();
assert.equal(foreign.painted, undefined, 'an editor this never painted is never touched');
});
test('a file VS Code does not tokenize at all is not painted', () => {
const big = Array.from({ length: 300001 }, () => '// TODO');
const vscode = fakeVscode();
const editor = fakeEditor(big, { visible: [[0, 10]] });
start(vscode, [editor]);
assert.deepEqual(editor.painted, [], 'over 300 000 lines');
const long = fakeEditor(['// TODO', 'x'.repeat(20 * 1024 * 1024)], { visible: [[0, 1]] });
start(fakeVscode(), [long]);
assert.deepEqual(long.painted, [], 'over 20 MiB');
const atLimit = fakeEditor(['// TODO', 'x'.repeat(20 * 1024 * 1024 - 8)], { visible: [[0, 1]] });
start(fakeVscode({ 'editor.maxTokenizationLineLength': 1e9 }), [atLimit]);
assert.deepEqual(atLimit.painted, ['0:TODO'], 'exactly 20 MiB is still tokenized');
const optOut = fakeEditor(big, { visible: [[0, 1]] });
start(fakeVscode({ 'editor.largeFileOptimizations': false }), [optOut]);
assert.equal(optOut.painted.length, 52, 'largeFileOptimizations off: VS Code tokenizes it, so it is painted');
});
test('paddedLines widens, clamps and merges the visible ranges', () => {
const range = (from, to) => ({ start: { line: from }, end: { line: to } });
assert.deepEqual(paddedLines([range(0, 10)], 30), [{ from: 0, to: 30 }]);
assert.deepEqual(paddedLines([range(300, 310), range(100, 110)], 1000),
[{ from: 50, to: 160 }, { from: 250, to: 360 }]);
assert.deepEqual(paddedLines([range(100, 110), range(150, 160)], 1000), [{ from: 50, to: 210 }]);
});
// ---- The shipped colour is readable on the built-in editor backgrounds.
/** `editor.background` of the built-in themes, per theme kind. */
const BACKGROUNDS = [
{ kind: 'dark', name: 'Dark Modern', background: '#1F1F1F' },
{ kind: 'dark', name: 'Dark+', background: '#1E1E1E' },
{ kind: 'light', name: 'Light Modern', background: '#FFFFFF' },
{ kind: 'light', name: 'Light+', background: '#FFFFFF' },
{ kind: 'highContrast', name: 'HC Dark', background: '#000000' },
{ kind: 'highContrastLight', name: 'HC Light', background: '#FFFFFF' },
];
/** WCAG relative luminance of an opaque `#RRGGBB`. */
function luminance(hex) {
const [r, g, b] = [1, 3, 5].map((at) => {
const c = parseInt(hex.slice(at, at + 2), 16) / 255;
return c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4;
});
return 0.2126 * r + 0.7152 * g + 0.0722 * b;
}
function contrast(a, b) {
const [high, low] = [luminance(a), luminance(b)].sort((x, y) => y - x);
return (high + 0.05) / (low + 0.05);
}
test('lucisv.commentKeyword is opaque and at least 4.5:1 on every built-in theme', () => {
const manifest = JSON.parse(fs.readFileSync(path.join(__dirname, 'package.json'), 'utf8'));
const colour = manifest.contributes.colors.find(({ id }) => id === COLOR_ID);
assert.ok(colour, `${COLOR_ID} is contributed`);
assert.equal(COLOR_ID.split('.').length, 2, 'exactly one dot in the colour id');
for (const { kind, name, background } of BACKGROUNDS) {
const foreground = colour.defaults[kind];
assert.match(foreground, /^#[0-9A-Fa-f]{6}$/, `${name}: opaque #RRGGBB`);
const ratio = contrast(foreground, background);
assert.ok(ratio >= 4.5, `${name}: ${foreground} on ${background} is ${ratio.toFixed(2)}:1`);
}
});