Files
lucisv/editors/vscode/commentKeywords_test.js
Guoliang ChenandClaude Mythos 5.2 71d13b5fbe
ci / checks (push) Successful in 1m0s
ci / corpus (push) Successful in 18s
ci / linux (push) Successful in 6m4s
release / build-and-publish (push) Successful in 5m31s
Release 0.66.2: every source file names its author
Every tracked file that can carry a comment (880 of them) now opens with
"Author: Guoliang Chen, a Senior Digital Design Engineer" and closes with
"Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love,
luciochen.com", in the file's own comment syntax. No behaviour change: the
diff outside the version bump and changelogs is comment lines only.

- tools/stamp_author.py: writes the lines; idempotent, `--check` lists
  what is missing. Headers go under a shebang and under Markdown front
  matter.
- Left alone: test fixtures, cases and snapshots (byte-exact inputs), JSON
  and JSONL, logs, images, lockfiles, docs/site/dist (regenerated) and the
  LICENSE files (already carry the copyright line).
- tools/linux_check.sh: --help reads its header from line 3, now that the
  author line sits under the shebang.
- tools/gates.sh green on this tree: 5 545 tests, corpus 814/6 as before.

Co-Authored-By: Claude Mythos 5.2 <[email protected]>
2026-11-24 12:11:09 -08:00

302 lines
13 KiB
JavaScript

// Author: Guoliang Chen, a Senior Digital Design Engineer
// 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`);
}
});
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com