archivo del paquete→ .shtukbase/packages/code-lib/checks/lib/lex.ts
checks/lib/lex.ts
312 líneas, 9.9 KB.
El archivo tal como está en el paquete: el código y sus comentarios no se traducen.
- // A rough, honest lexer for TypeScript/JavaScript, Python and Rust: no parser, no dependencies.
- // `mask` returns the source with the contents of comments and strings replaced by spaces (newlines kept, so
- // offsets and line numbers stay the same) plus the list of strings and comments it saw. Every heuristic of the
- // code-* packages works on the masked text: a brace or a keyword inside a string or a comment never counts.
- // Known limits: a JS regex literal is told from division by the token before it; Rust char literals vs
- // lifetimes by the next characters; Python f-string expressions are masked like the rest of the string.
- export type Lang = 'ts' | 'py' | 'rs';
- export type Str = { start: number; end: number; line: number; value: string };
- export type Comment = { start: number; end: number; line: number; text: string; block: boolean };
- export type Masked = { code: string; strings: Str[]; comments: Comment[] };
- export function langOf(path: string): Lang | null {
- const m = /\.([A-Za-z0-9]+)$/.exec(path);
- const ext = m ? m[1].toLowerCase() : '';
- if (['ts', 'tsx', 'mts', 'cts', 'js', 'jsx', 'mjs', 'cjs'].includes(ext)) return 'ts';
- if (ext === 'py' || ext === 'pyi') return 'py';
- if (ext === 'rs') return 'rs';
- return null;
- }
- const REGEX_BEFORE = new Set('(,=:[!&|?{};+-*%<>~^'.split(''));
- const REGEX_KEYWORDS = /\b(return|typeof|case|do|else|in|of|new|delete|void|throw|yield|await)\s*$/;
- export function mask(src: string, lang: Lang): Masked {
- const out = src.split('');
- const strings: Str[] = [];
- const comments: Comment[] = [];
- const n = src.length;
- const blank = (a: number, b: number) => {
- for (let k = a; k < b; k++) if (out[k] !== '\n') out[k] = ' ';
- };
- const addStr = (qStart: number, cStart: number, cEnd: number, qEnd: number) => {
- strings.push({ start: qStart, end: qEnd, line: 0, value: src.slice(cStart, cEnd) });
- blank(cStart, cEnd);
- };
- const addComment = (a: number, b: number, block: boolean) => {
- comments.push({ start: a, end: b, line: 0, text: src.slice(a, b), block });
- blank(a, b);
- };
- /** End of a simple quoted string starting at the quote `i`; stops at a newline when `oneLine`. */
- const quoted = (i: number, q: string, oneLine: boolean, escapes = true): number => {
- let k = i + 1;
- while (k < n) {
- const c = src[k];
- if (escapes && c === '\\') { k += 2; continue; }
- if (c === q) return k;
- if (oneLine && c === '\n') return k - 1;
- k++;
- }
- return n - 1;
- };
- /** The last significant (non-space) char of the masked output before `i`. */
- const prevSig = (i: number): number => {
- let k = i - 1;
- while (k >= 0 && /\s/.test(out[k])) k--;
- return k;
- };
- // TypeScript template literal with ${} nesting: returns the index of the closing backtick.
- const template = (i: number): number => {
- let k = i + 1;
- let segStart = k;
- let value = '';
- while (k < n) {
- const c = src[k];
- if (c === '\\') { k += 2; continue; }
- if (c === '`') {
- value += src.slice(segStart, k);
- blank(segStart, k);
- strings.push({ start: i, end: k, line: 0, value });
- return k;
- }
- if (c === '$' && src[k + 1] === '{') {
- value += src.slice(segStart, k) + '${…}';
- blank(segStart, k);
- k = tsCode(k + 2, true); // returns index of the closing }
- segStart = k + 1;
- k++;
- continue;
- }
- k++;
- }
- blank(segStart, n);
- return n - 1;
- };
- // TypeScript code from `start`; when `nested`, stops at the } that closes a template expression.
- const tsCode = (start: number, nested: boolean): number => {
- let depth = 0;
- let i = start;
- while (i < n) {
- const c = src[i];
- const d = src[i + 1];
- if (c === '/' && d === '/') {
- let e = src.indexOf('\n', i);
- if (e < 0) e = n;
- addComment(i, e, false);
- i = e;
- continue;
- }
- if (c === '/' && d === '*') {
- let e = src.indexOf('*/', i + 2);
- e = e < 0 ? n : e + 2;
- addComment(i, e, true);
- i = e;
- continue;
- }
- if (c === "'" || c === '"') {
- const e = quoted(i, c, true);
- addStr(i, i + 1, e, e);
- i = e + 1;
- continue;
- }
- if (c === '`') {
- i = template(i) + 1;
- continue;
- }
- if (c === '/') {
- const p = prevSig(i);
- const before = src.slice(Math.max(0, i - 12), i);
- const pc = p >= 0 ? out[p] : '';
- if (p < 0 || REGEX_BEFORE.has(pc) || REGEX_KEYWORDS.test(before)) {
- // a regex literal: up to the unescaped / outside a [class]
- let k = i + 1;
- let cls = false;
- while (k < n && src[k] !== '\n') {
- const ch = src[k];
- if (ch === '\\') { k += 2; continue; }
- if (ch === '[') cls = true;
- else if (ch === ']') cls = false;
- else if (ch === '/' && !cls) break;
- k++;
- }
- if (k < n && src[k] === '/') {
- addStr(i, i + 1, k, k);
- i = k + 1;
- while (i < n && /[a-z]/.test(src[i])) i++;
- continue;
- }
- }
- i++;
- continue;
- }
- if (nested) {
- if (c === '{') depth++;
- else if (c === '}') {
- if (depth === 0) return i;
- depth--;
- }
- }
- i++;
- }
- return n;
- };
- const pyCode = () => {
- let i = 0;
- while (i < n) {
- const c = src[i];
- if (c === '#') {
- let e = src.indexOf('\n', i);
- if (e < 0) e = n;
- addComment(i, e, false);
- i = e;
- continue;
- }
- if (c === "'" || c === '"') {
- // prefix letters (r, b, f, u) stay in the code; a raw string still ends at an unescaped quote
- const triple = src.slice(i, i + 3) === c.repeat(3);
- if (triple) {
- let k = i + 3;
- while (k < n) {
- if (src[k] === '\\') { k += 2; continue; }
- if (src.slice(k, k + 3) === c.repeat(3)) break;
- k++;
- }
- const e = Math.min(k, n);
- addStr(i, i + 3, e, e + 2);
- i = e + 3;
- continue;
- }
- const e = quoted(i, c, true, true);
- addStr(i, i + 1, e, e);
- i = e + 1;
- continue;
- }
- i++;
- }
- };
- const rsCode = () => {
- let i = 0;
- while (i < n) {
- const c = src[i];
- const d = src[i + 1];
- if (c === '/' && d === '/') {
- let e = src.indexOf('\n', i);
- if (e < 0) e = n;
- addComment(i, e, false);
- i = e;
- continue;
- }
- if (c === '/' && d === '*') {
- let k = i + 2;
- let depth = 1;
- while (k < n && depth > 0) {
- if (src[k] === '/' && src[k + 1] === '*') { depth++; k += 2; continue; }
- if (src[k] === '*' && src[k + 1] === '/') { depth--; k += 2; continue; }
- k++;
- }
- addComment(i, k, true);
- i = k;
- continue;
- }
- // raw strings: r"..", r#".."#, br#".."#
- const raw = /^b?r(#*)"/.exec(src.slice(i, i + 40));
- if (raw && !/[A-Za-z0-9_]/.test(src[i - 1] ?? '')) {
- const hashes = raw[1];
- const open = i + raw[0].length;
- const close = src.indexOf('"' + hashes, open);
- const e = close < 0 ? n : close;
- addStr(i, open, e, e + hashes.length);
- i = e + 1 + hashes.length;
- continue;
- }
- if (c === '"') {
- const e = quoted(i, '"', false);
- addStr(i, i + 1, e, e);
- i = e + 1;
- continue;
- }
- if (c === "'") {
- // char literal or lifetime
- if (d === '\\') {
- const e = src.indexOf("'", i + 3);
- if (e > 0 && e - i < 12) { addStr(i, i + 1, e, e); i = e + 1; continue; }
- } else {
- const cp = src.codePointAt(i + 1) ?? 0;
- const w = cp > 0xffff ? 2 : 1;
- if (src[i + 1 + w] === "'") { addStr(i, i + 1, i + 1 + w, i + 1 + w); i = i + 2 + w; continue; }
- }
- i++;
- continue;
- }
- i++;
- }
- };
- if (lang === 'ts') tsCode(0, false);
- else if (lang === 'py') pyCode();
- else rsCode();
- let code = out.join('');
- if (lang === 'rs') code = dropRustTests(code);
- strings.sort((a, b) => a.start - b.start);
- comments.sort((a, b) => a.start - b.start);
- const starts = lineStarts(src);
- for (const x of [...strings, ...comments]) x.line = lineOf(starts, x.start);
- return { code, strings, comments };
- }
- /** Blanks `#[cfg(test)] mod x { ... }` blocks: unit tests inside a Rust file are not the code the norms judge. */
- function dropRustTests(code: string): string {
- const re = /#\[cfg\(test\)\]\s*(?:pub(?:\([^)]*\))?\s+)?mod\s+\w+\s*\{/g;
- let m: RegExpExecArray | null;
- let out = code;
- while ((m = re.exec(code))) {
- const open = m.index + m[0].length - 1;
- const close = matchClose(code, open);
- if (close < 0) continue;
- out = out.slice(0, m.index) + out.slice(m.index, close + 1).replace(/[^\n]/g, ' ') + out.slice(close + 1);
- re.lastIndex = close + 1;
- }
- return out;
- }
- const PAIRS: Record<string, string> = { '(': ')', '[': ']', '{': '}' };
- /** The index of the bracket that closes the one at `open` in masked code; -1 when it is not closed. */
- export function matchClose(code: string, open: number): number {
- const o = code[open];
- const c = PAIRS[o];
- if (!c) return -1;
- let depth = 0;
- for (let k = open; k < code.length; k++) {
- const ch = code[k];
- if (ch === o) depth++;
- else if (ch === c) {
- depth--;
- if (depth === 0) return k;
- }
- }
- return -1;
- }
- /** Offsets of line starts, for turning an offset into a 1-based line number. */
- export function lineStarts(text: string): number[] {
- const s = [0];
- for (let k = 0; k < text.length; k++) if (text[k] === '\n') s.push(k + 1);
- return s;
- }
- export function lineOf(starts: number[], offset: number): number {
- let lo = 0;
- let hi = starts.length - 1;
- while (lo < hi) {
- const mid = (lo + hi + 1) >> 1;
- if (starts[mid] <= offset) lo = mid;
- else hi = mid - 1;
- }
- return lo + 1;
- }