Files
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

237 lines
8.4 KiB
JavaScript

// Where the comments are, and which words inside them to highlight — pure,
// no `vscode`, so every rule here is tested with plain node
// (docs/features/comment-highlighting).
//
// The comment rules are the TextMate grammar's, not the lexer's, on purpose:
// a keyword is highlighted where the user *sees* comment colouring, and that
// colouring is the grammar's. `commentScan_test.js` pins the grammar rules
// this file mirrors, so an edit to one without the other fails the build.
//
// The grammar (`syntaxes/systemverilog.tmLanguage.json`) has exactly two rules
// that decide what is comment: `//.*` and `/\*` … `\*/` (which may span
// lines), and one that hides a `//` or `/*` from them — a string, `"` … `"`
// or end of line, with `\\.` escapes. Every other top-level rule matches only
// characters that can never begin those three (backtick names, `$` names,
// numbers, keywords), so it can never swallow or reveal a comment start and
// this scan can ignore it.
/** The words highlighted unless `lucisv.commentKeywords.builtIn` is off. */
const BUILT_IN_WORDS = ['TODO', 'FIXME', 'FIX_ME', 'TBD'];
/** At most this many custom words are honoured; the rest are dropped. */
const MAX_CUSTOM_WORDS = 50;
/** A custom word longer than this is dropped. */
const MAX_WORD_LENGTH = 40;
/** An identifier character: a match may not have one on either side. */
const WORD_CHAR = '[A-Za-z0-9_$]';
/** The next thing that can start a comment or a string. */
const OPENER = /\/\/|\/\*|"/g;
/**
* The comment spans of one line, given whether it starts inside a block
* comment, and whether the next line does.
*
* Each span is `[start, end, bodyStart, bodyEnd]`: the whole comment with
* its delimiters, then the text between them, all as `[start, end)` offsets in
* UTF-16 units — VS Code's columns.
*/
function scanLine(text, inBlock) {
const spans = [];
let at = 0;
if (inBlock) {
const close = text.indexOf('*/');
if (close < 0) return { spans: [[0, text.length, 0, text.length]], inBlock: true };
spans.push([0, close + 2, 0, close]);
at = close + 2;
}
for (;;) {
OPENER.lastIndex = at;
const opener = OPENER.exec(text);
if (!opener) return { spans, inBlock: false };
const start = opener.index;
if (opener[0] === '//') {
spans.push([start, text.length, start + 2, text.length]);
return { spans, inBlock: false };
}
if (opener[0] === '/*') {
const close = text.indexOf('*/', start + 2);
if (close < 0) {
spans.push([start, text.length, start + 2, text.length]);
return { spans, inBlock: true };
}
spans.push([start, close + 2, start + 2, close]);
at = close + 2;
} else {
at = stringEnd(text, start + 1);
}
}
}
/**
* Where a string that opened just before `at` ends: after its closing quote,
* or at the end of the line. A backslash escapes the next character, if the
* line has one — the grammar's `\\.` cannot match the line break.
*/
function stringEnd(text, at) {
while (at < text.length) {
const c = text[at];
if (c === '\\') at += 2;
else if (c === '"') return at + 1;
else at += 1;
}
return text.length;
}
/**
* The words to highlight, from the settings: the built-ins (unless turned
* off) and every usable custom word, without duplicates.
*
* A custom word is usable when it is a string of 1 to `MAX_WORD_LENGTH`
* characters with no whitespace; anything else is skipped, as is everything
* past the first `MAX_CUSTOM_WORDS`. Returns the words and the skipped
* entries, so the caller can say what it ignored.
*/
function chooseWords({ builtIn = true, custom = [], caseSensitive = true } = {}) {
const words = builtIn === false ? [] : [...BUILT_IN_WORDS];
const skipped = [];
const list = Array.isArray(custom) ? custom : [];
for (const [index, entry] of list.entries()) {
const usable = typeof entry === 'string' && entry.length > 0
&& entry.length <= MAX_WORD_LENGTH && !/\s/.test(entry);
if (usable && index < MAX_CUSTOM_WORDS) words.push(entry);
else skipped.push(entry);
}
const seen = new Set();
const unique = words.filter((word) => {
const key = caseSensitive === false ? word.toLowerCase() : word;
if (seen.has(key)) return false;
seen.add(key);
return true;
});
return { words: unique, skipped };
}
/** `text` with every regular-expression metacharacter escaped. */
function escapeRegExp(text) {
return text.replace(/[.*+?^${}()|[\]\\/]/g, '\\$&');
}
/**
* One global regular expression that finds any of `words` as a whole word,
* or `null` when there are none.
*
* Whole word the way `\b` means it, with `$` counted as a word character
* (Verilog's identifiers have it): a word that starts with a word character
* may not have one just before it, and one that ends with a word character
* may not have one just after. So `TODO` skips `TODO_reg` and `myTODO`, and
* `REVIEW:` matches in `REVIEW:x`.
*
* Every word is matched literally — escaped, never interpreted — so a setting
* cannot inject a pattern. The alternation is of plain literals, longest
* first so a word wins over its own prefix, each between at most two
* one-character lookarounds: no quantifier, nothing to backtrack
* catastrophically on.
*/
function wordMatcher(words, caseSensitive = true) {
if (!words.length) return null;
const startsWord = new RegExp(`^${WORD_CHAR}`);
const endsWord = new RegExp(`${WORD_CHAR}$`);
const alternatives = [...words]
.sort((a, b) => b.length - a.length)
.map((word) => (startsWord.test(word) ? `(?<!${WORD_CHAR})` : '')
+ escapeRegExp(word)
+ (endsWord.test(word) ? `(?!${WORD_CHAR})` : ''));
const flags = caseSensitive === false ? 'gi' : 'g';
return new RegExp(alternatives.join('|'), flags);
}
/**
* The `[start, end)` matches of `matcher` inside the bodies of `spans` — never
* across a comment's own delimiters, whatever a custom word holds.
*/
function wordsInSpans(text, spans, matcher) {
const found = [];
for (const [, , start, end] of spans) {
const inside = text.slice(start, end);
matcher.lastIndex = 0;
for (const match of inside.matchAll(matcher)) {
found.push([start + match.index, start + match.index + match[0].length]);
}
}
return found;
}
/**
* Per document: whether each line starts inside a block comment, computed
* lazily from the top and kept until an edit above it invalidates it — so
* scrolling or typing never rescans the lines above the edit.
*
* `maxLineLength` mirrors VS Code's `editor.maxTokenizationLineLength`: the
* editor does not tokenize a line that long (`length >= max`) and carries the
* state across it unchanged, so it shows no comment there and neither do we.
*/
class LineStates {
constructor() {
/** `starts[i]`: line `i` begins inside a block comment. Line 0 never does. */
this.starts = [false];
}
/** Lines from `line` on may have changed. */
invalidateFrom(line) {
this.starts.length = Math.max(1, Math.min(this.starts.length, line + 1));
}
/** Whether `line` starts inside a block comment. */
startOf(line, lineText, maxLineLength) {
while (this.starts.length <= line) {
const previous = this.starts.length - 1;
const text = lineText(previous);
const inBlock = this.starts[previous];
this.starts.push(text.length >= maxLineLength ? inBlock : scanLine(text, inBlock).inBlock);
}
return this.starts[line];
}
/** Record what a scan of `line` found for the next one, if that is new. */
recordNext(line, inBlock) {
if (this.starts.length === line + 1) this.starts.push(inBlock);
}
}
/**
* The keyword ranges `{ line, start, end }` on lines `from`..`to` (inclusive)
* of a document read through `lineText`.
*/
function keywordRanges({ states, lineText, from, to, matcher, maxLineLength }) {
const ranges = [];
if (!matcher) return ranges;
for (let line = from; line <= to; line += 1) {
const text = lineText(line);
const inBlock = states.startOf(line, lineText, maxLineLength);
if (text.length >= maxLineLength) {
states.recordNext(line, inBlock);
continue;
}
const { spans, inBlock: next } = scanLine(text, inBlock);
states.recordNext(line, next);
for (const [start, end] of wordsInSpans(text, spans, matcher)) ranges.push({ line, start, end });
}
return ranges;
}
module.exports = {
BUILT_IN_WORDS,
MAX_CUSTOM_WORDS,
MAX_WORD_LENGTH,
scanLine,
chooseWords,
escapeRegExp,
wordMatcher,
wordsInSpans,
LineStates,
keywordRanges,
};