Files
lucisv/editors/vscode/commentScan_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

249 lines
10 KiB
JavaScript

// Author: Guoliang Chen, a Senior Digital Design Engineer
// commentScan.js: the comment rules it mirrors are the grammar's, the words
// are matched literally and as whole words, and the incremental line states
// always agree with a scan from the top (docs/features/comment-highlighting).
//
// node --test commentScan_test.js
const assert = require('assert/strict');
const fs = require('fs');
const path = require('path');
const test = require('node:test');
const {
BUILT_IN_WORDS, MAX_CUSTOM_WORDS, MAX_WORD_LENGTH, scanLine, chooseWords, escapeRegExp,
wordMatcher, wordsInSpans, LineStates, keywordRanges,
} = require('./commentScan');
const grammar = JSON.parse(
fs.readFileSync(path.join(__dirname, 'syntaxes', 'systemverilog.tmLanguage.json'), 'utf8'),
);
/** The comment columns of each line, as `.`/`#`, scanned top to bottom. */
function picture(lines) {
let inBlock = false;
return lines.map((line) => {
const result = scanLine(line, inBlock);
inBlock = result.inBlock;
const marks = Array.from(line, () => '.');
for (const [start, end] of result.spans) marks.fill('#', start, end);
return marks.join('');
});
}
/** The highlighted words of a whole document, as `line:text` strings. */
function highlighted(lines, words = BUILT_IN_WORDS, options = {}) {
const ranges = keywordRanges({
states: new LineStates(),
lineText: (line) => lines[line],
from: 0,
to: lines.length - 1,
matcher: wordMatcher(words, options.caseSensitive),
maxLineLength: options.maxLineLength || 20000,
});
return ranges.map(({ line, start, end }) => `${line}:${lines[line].slice(start, end)}`);
}
test('the grammar still decides comments with exactly the rules this mirrors', () => {
assert.deepEqual(grammar.repository.comments, {
patterns: [
{ name: 'comment.line.double-slash.systemverilog', match: '//.*' },
{ name: 'comment.block.systemverilog', begin: '/\\*', end: '\\*/' },
],
});
assert.deepEqual(grammar.repository.strings, {
name: 'string.quoted.double.systemverilog',
begin: '"',
end: '"|$',
patterns: [{ name: 'constant.character.escape.systemverilog', match: '\\\\.' }],
});
assert.deepEqual(grammar.patterns.slice(0, 2), [{ include: '#comments' }, { include: '#strings' }]);
});
test('no other top-level grammar rule can match a "/" or a quote', () => {
// If one could, it might swallow a comment opener or reveal one this scan
// hides, and the scan would have to model it. A rule built only of literal
// letters, `\b`, `\s`, digits and classes without `/` or `"` cannot.
const others = grammar.patterns.slice(2).map(({ include }) => grammar.repository[include.slice(1)]);
const regexes = others.flatMap((rule) => (rule.patterns || [rule]).map((r) => r.match));
assert.ok(regexes.length >= 5);
for (const source of regexes) {
assert.equal(typeof source, 'string', 'every other rule is a single-line match');
const unescaped = source.replace(/\\./g, '');
for (const risky of ['/', '"', '.', '[^']) {
assert.ok(!unescaped.includes(risky), `${source} contains ${risky}`);
}
// QA 2026-11-19: also Oniguruma's any-char/negated escapes (`\H` non-hex,
// `\O`, `\X`, `\R`, `\P{…}`/`\p{…}`), code-point escapes that can spell
// `/` or `"` (`\x2F`, `"`, octal `\057`), and POSIX classes.
for (const escape of ['\\S', '\\W', '\\D', '\\N', '\\/', '\\H', '\\O', '\\X', '\\R',
'\\P', '\\p', '\\x', '\\u', '\\0', '[[:']) {
assert.ok(!source.includes(escape), `${source} contains ${escape}`);
}
}
});
test('comments: line, block, strings that hide them, and blocks across lines', () => {
const lines = [
'assign s = "a // b"; // c',
'x = "q\\" // still"; /* d */ y;',
'unterminated "string // to the end',
'/* opens',
' " is not a string here',
'closes */ z = "/*";',
'/*/ not closed',
'still */ q',
'`define M(a) a // macro text',
'(* full_case *) case (x)',
'a = "back\\\\"; // after',
'a = "slash at end \\',
'/**/ b /***/ c',
];
// Copied from vscode-textmate's own tokenization of these lines with this
// grammar (docs/features/comment-highlighting, "Agreement"), not hand-counted.
assert.deepEqual(picture(lines), [
'.....................####',
'....................#######...',
'..................................',
'########',
'#########################',
'#########..........',
'##############',
'########..',
'...............#############',
'........................',
'..............########',
'...................',
'####...#####..',
]);
});
test('spans carry their bodies, without the delimiters', () => {
assert.deepEqual(scanLine('a /* b */ // c', false).spans, [[2, 9, 4, 7], [10, 14, 12, 14]]);
assert.deepEqual(scanLine('x */ y', true).spans, [[0, 4, 0, 2]]);
assert.deepEqual(scanLine('x', true), { spans: [[0, 1, 0, 1]], inBlock: true });
});
test('the built-ins are highlighted in comments and nowhere else', () => {
assert.deepEqual(
highlighted([
'// TODO: fix, FIXME, FIX_ME and TBD',
'wire TODO_reg; // TODO_reg myTODO $TODO TODO$ TODO1 xTBD',
'string s = "TODO // TODO"; // TODO',
'TODO = 1; /* TBD */ FIXME',
'/* block',
' (TODO) [TBD] {FIX_ME}.',
'*/ TODO',
'//TODO//FIXME',
'/*TODO*/',
'todo Todo // todo Todo tbd',
]),
['0:TODO', '0:FIXME', '0:FIX_ME', '0:TBD', '2:TODO', '3:TBD', '5:TODO', '5:TBD', '5:FIX_ME',
'7:TODO', '7:FIXME', '8:TODO'],
);
});
test('case-insensitive matching is opt-in', () => {
assert.deepEqual(highlighted(['// todo Todo TODO todo_x'], BUILT_IN_WORDS, { caseSensitive: false }),
['0:todo', '0:Todo', '0:TODO']);
assert.deepEqual(highlighted(['// todo Todo'], BUILT_IN_WORDS, { caseSensitive: true }), []);
});
test('custom words are literal: metacharacters mean themselves', () => {
const words = ['a.b', '(.*)+', '[x]', '\\d', 'c|d', '^e$', 'f?', 'g{2}', '$h', 'i/j'];
assert.deepEqual(
highlighted(['// axb a.b (.*)+ aaa [x] x \\d 1 c|d c d ^e$ e f? f g{2} gg $h i/j'], words),
['0:a.b', '0:(.*)+', '0:[x]', '0:\\d', '0:c|d', '0:^e$', '0:f?', '0:g{2}', '0:$h', '0:i/j'],
);
assert.equal(escapeRegExp('.*+?^${}()|[]\\/'), '\\.\\*\\+\\?\\^\\$\\{\\}\\(\\)\\|\\[\\]\\\\\\/');
});
test('whole words follow \\b, with $ as a word character', () => {
const words = ['REVIEW:', '@note', 'HACK'];
assert.deepEqual(
highlighted(['// REVIEW:x xREVIEW: a@note @notes HACK_mode HACK$ (HACK) HACK'], words),
['0:REVIEW:', '0:@note', '0:HACK', '0:HACK'],
);
});
test('a word wins over its own prefix', () => {
assert.deepEqual(highlighted(['// TODO! TODO'], ['TODO', 'TODO!']), ['0:TODO!', '0:TODO']);
});
test('a custom word cannot reach into a comment delimiter', () => {
assert.deepEqual(highlighted(['// x /* y */ z', 'a /** b **/'], ['//', '/*', '*/', '**', '*']),
['0:/*', '0:*/', '1:*', '1:*'], 'inside a line comment, "/* y */" is only text');
});
test('chooseWords: built-ins, caps, junk and duplicates', () => {
assert.deepEqual(chooseWords().words, BUILT_IN_WORDS);
assert.deepEqual(chooseWords({ builtIn: false }).words, []);
assert.deepEqual(chooseWords({ builtIn: false, custom: ['XXX', 'XXX', 'HACK'] }).words, ['XXX', 'HACK']);
const junk = ['', 'two words', 'tab\there', 'x'.repeat(MAX_WORD_LENGTH + 1), 7, null, { a: 1 }];
const { words, skipped } = chooseWords({ custom: [...junk, 'OK'] });
assert.deepEqual(words, [...BUILT_IN_WORDS, 'OK']);
assert.deepEqual(skipped, junk);
assert.deepEqual(chooseWords({ custom: 'TODO' }).words, BUILT_IN_WORDS, 'a non-array is no words');
const many = Array.from({ length: MAX_CUSTOM_WORDS + 5 }, (_, i) => `W${i}`);
const capped = chooseWords({ builtIn: false, custom: many });
assert.equal(capped.words.length, MAX_CUSTOM_WORDS);
assert.equal(capped.skipped.length, 5);
assert.deepEqual(chooseWords({ custom: ['todo'], caseSensitive: false }).words, BUILT_IN_WORDS);
assert.deepEqual(chooseWords({ custom: ['todo'] }).words, [...BUILT_IN_WORDS, 'todo']);
assert.equal(wordMatcher([]), null);
});
test('the worst words the caps allow stay fast on the longest line VS Code tokenizes', () => {
const words = Array.from({ length: MAX_CUSTOM_WORDS }, (_, i) => 'a'.repeat(MAX_WORD_LENGTH - (i % 3)) + i % 3);
const line = `// ${'a'.repeat(19990)}`;
const started = process.hrtime.bigint();
wordsInSpans(line, scanLine(line, false).spans, wordMatcher(words));
const ms = Number(process.hrtime.bigint() - started) / 1e6;
assert.ok(ms < 2000, `took ${ms.toFixed(0)} ms`);
});
test('a line VS Code will not tokenize carries the state and highlights nothing', () => {
const lines = ['/* open', `x ${'y'.repeat(50)} */ // TODO`, 'still open TODO */'];
assert.deepEqual(highlighted(lines, BUILT_IN_WORDS, { maxLineLength: 40 }), ['2:TODO']);
assert.deepEqual(highlighted(lines, BUILT_IN_WORDS, { maxLineLength: 1000 }), ['1:TODO']);
});
/** A small deterministic PRNG, so a failure reproduces. */
function prng(seed) {
let state = seed;
return () => {
state = (state * 1103515245 + 12345) % 2147483648;
return state / 2147483648;
};
}
test('incremental line states, painted or probed, always equal a scan from the top', () => {
const random = prng(71);
const pieces = ['/*', '*/', '//', '"', 'x', ' ', 'TODO', '\\'];
const line = () => Array.from({ length: 1 + Math.floor(random() * 6) },
() => pieces[Math.floor(random() * pieces.length)]).join('');
const lines = Array.from({ length: 40 }, line);
const states = new LineStates();
const lineText = (at) => lines[at];
for (let round = 0; round < 300; round += 1) {
const at = Math.floor(random() * lines.length);
const kind = random();
if (kind < 0.4) lines[at] = line();
else if (kind < 0.7) lines.splice(at, 0, line());
else if (lines.length > 1) lines.splice(at, 1);
states.invalidateFrom(at);
if (random() < 0.5) {
// A paint of some window, which records states as a side effect.
const from = Math.floor(random() * lines.length);
const to = Math.min(lines.length - 1, from + Math.floor(random() * 8));
keywordRanges({ states, lineText, from, to, matcher: wordMatcher(['TODO']), maxLineLength: 20000 });
}
const probe = Math.floor(random() * lines.length);
const fresh = new LineStates();
assert.equal(states.startOf(probe, lineText, 20000), fresh.startOf(probe, lineText, 20000),
`round ${round}, line ${probe}`);
}
});
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com