файл пакета→ .shtukbase/packages/code-lib/checks/lib/units.ts
checks/lib/units.ts
404 строки, 17.1 КБ.
Файл как есть в пакете: код и комментарии в нём не переводятся.
- // Functions, classes and imports found in masked code by regular expressions and bracket matching.
- // Rough on purpose: no parser. What it finds:
- // TypeScript/JavaScript — `function f(`, `const f = (…) => {`, `f: (…) => {`, `f = async (…) => {`, class and object
- // methods `f(…) {` at the start of a line; anonymous callbacks are part of the function around them.
- // Python — `def f(` with its indented body; `class X`.
- // Rust — `fn f(` with a body (trait declarations without a body are skipped); `impl … {` blocks as classes.
- import { type Lang, lineOf, matchClose } from './lex.ts';
- import type { Source } from './scan.ts';
- export type Fn = {
- name: string;
- line: number; // line of the signature
- endLine: number;
- params: string[]; // parameter names ('' for a destructured or unnamed one); self/this/cls dropped
- paramText: string[]; // the raw parameter text, one per parameter
- hasSelf: boolean; // a method: Rust `self`, Python `self`/`cls`, TypeScript method inside a class
- exported: boolean;
- bodyStart: number; // offset of the first char inside the body
- bodyEnd: number; // offset of the closing } (TypeScript, Rust) or of the end of the body (Python)
- indent: number; // Python: the indent of `def`
- traitImpl: boolean; // Rust: inside `impl Trait for Type`, where the signature is the trait's, not the author's
- };
- export type Cls = { name: string; line: number; endLine: number };
- const TS_NOT_NAMES = new Set(['if', 'for', 'while', 'switch', 'catch', 'return', 'function', 'with', 'else', 'do', 'try', 'typeof', 'new', 'await', 'yield', 'super', 'import', 'export', 'constructor_']);
- /** Splits a parameter list at top-level commas. `=>` and `->` do not close an angle bracket. */
- export function splitTop(text: string): string[] {
- const out: string[] = [];
- let depth = 0;
- let cur = '';
- for (let k = 0; k < text.length; k++) {
- const c = text[k];
- if ('([{<'.includes(c)) depth++;
- else if (')]}'.includes(c)) depth--;
- else if (c === '>' && text[k - 1] !== '=' && text[k - 1] !== '-') depth--;
- if (c === ',' && depth <= 0) {
- out.push(cur);
- cur = '';
- depth = 0;
- continue;
- }
- cur += c;
- }
- out.push(cur);
- return out.map((x) => x.trim()).filter(Boolean);
- }
- function paramName(p: string, lang: Lang): string {
- let s = p.replace(/^\.\.\.|^\*{1,2}/, '').trim();
- if (lang === 'ts') s = s.replace(/^(public|private|protected|readonly|override)\s+/g, '');
- if (lang === 'rs') s = s.replace(/^mut\s+/, '');
- const m = /^([A-Za-z_$][\w$]*)/.exec(s);
- return m ? m[1] : '';
- }
- /** Skips a type annotation after `)`: returns the offset of the body `{`, or -1 for no body (`;`, `=>` expr, end). */
- function bodyOpen(code: string, from: number, lang: Lang): number {
- let k = from;
- let depth = 0;
- while (k < code.length) {
- const c = code[k];
- if (depth === 0) {
- if (c === '{') {
- // a TypeScript object type literal right after `:` is part of the type
- const before = code.slice(from, k).trim();
- if (lang === 'ts' && /:$|[|&<,]$/.test(before)) {
- const e = matchClose(code, k);
- if (e < 0) return -1;
- k = e + 1;
- continue;
- }
- return k;
- }
- if (c === ';' || c === '}') return -1;
- if (lang === 'ts' && c === '=' && code[k + 1] === '>') {
- let j = k + 2;
- while (/\s/.test(code[j] ?? '')) j++;
- return code[j] === '{' ? j : -1;
- }
- if (lang === 'ts' && c === '\n') {
- // a method signature in an interface or an overload ends at the line end
- const rest = code.slice(from, k).trim();
- if (rest === '' || rest.startsWith(':')) { k++; continue; }
- }
- }
- if ('([<'.includes(c)) depth++;
- else if (')]'.includes(c)) depth--;
- else if (c === '>' && code[k - 1] !== '=' && code[k - 1] !== '-') depth = Math.max(0, depth - 1);
- k++;
- }
- return -1;
- }
- /** Skips `<…>` generics starting at `k` (which must be `<`); returns the offset after it. */
- function skipGenerics(code: string, k: number): number {
- let depth = 0;
- for (; k < code.length; k++) {
- if (code[k] === '<') depth++;
- else if (code[k] === '>' && code[k - 1] !== '-' && code[k - 1] !== '=') {
- depth--;
- if (depth === 0) return k + 1;
- } else if (code[k] === '{' || code[k] === ';') return k;
- }
- return k;
- }
- const cache = new WeakMap<Source, { fns: Fn[]; classes: Cls[] }>();
- export function functions(src: Source): Fn[] {
- return parse(src).fns;
- }
- export function classes(src: Source): Cls[] {
- return parse(src).classes;
- }
- function parse(src: Source): { fns: Fn[]; classes: Cls[] } {
- const hit = cache.get(src);
- if (hit) return hit;
- const res = src.lang === 'py' ? parsePy(src) : src.lang === 'rs' ? parseRs(src) : parseTs(src);
- res.fns.sort((a, b) => a.bodyStart - b.bodyStart);
- cache.set(src, res);
- return res;
- }
- function mkFn(src: Source, name: string, sigAt: number, pOpen: number, pClose: number, open: number, close: number, extra: Partial<Fn>): Fn {
- const parts = splitTop(src.code.slice(pOpen + 1, pClose));
- const raw = parts;
- let hasSelf = !!extra.hasSelf;
- const keep: string[] = [];
- const keepText: string[] = [];
- for (const p of raw) {
- const t = p.trim();
- if (src.lang === 'rs' && /^(&\s*('\w+\s+)?(mut\s+)?)?(mut\s+)?self\b/.test(t)) { hasSelf = true; continue; }
- if (src.lang === 'py' && /^(self|cls)\b/.test(t) && keep.length === 0 && keepText.length === 0) { hasSelf = true; continue; }
- if (src.lang === 'py' && (t === '*' || t === '/')) continue;
- if (src.lang === 'ts' && /^this\s*:/.test(t)) continue;
- keep.push(paramName(t, src.lang));
- keepText.push(t);
- }
- return {
- name,
- line: lineOf(src.starts, sigAt),
- endLine: lineOf(src.starts, close),
- params: keep,
- paramText: keepText,
- hasSelf,
- exported: !!extra.exported,
- bodyStart: open + 1,
- bodyEnd: close,
- indent: extra.indent ?? 0,
- traitImpl: !!extra.traitImpl,
- };
- }
- function parseTs(src: Source): { fns: Fn[]; classes: Cls[] } {
- const code = src.code;
- const fns: Fn[] = [];
- const classes: Cls[] = [];
- const seen = new Set<number>();
- const add = (name: string, sigAt: number, pOpen: number, extra: Partial<Fn>) => {
- if (seen.has(pOpen)) return;
- const pClose = matchClose(code, pOpen);
- if (pClose < 0) return;
- const open = bodyOpen(code, pClose + 1, 'ts');
- if (open < 0) return;
- const close = matchClose(code, open);
- if (close < 0) return;
- seen.add(pOpen);
- fns.push(mkFn(src, name, sigAt, pOpen, pClose, open, close, extra));
- };
- let m: RegExpExecArray | null;
- const cls = /^[ \t]*(?:export\s+)?(?:default\s+)?(?:abstract\s+)?class\s+([A-Za-z_$][\w$]*)[^{]*\{/gm;
- while ((m = cls.exec(code))) {
- const open = m.index + m[0].length - 1;
- const close = matchClose(code, open);
- if (close > 0) classes.push({ name: m[1], line: lineOf(src.starts, m.index), endLine: lineOf(src.starts, close) });
- }
- const inClass = (at: number) => classes.some((c) => lineOf(src.starts, at) > c.line && lineOf(src.starts, at) <= c.endLine);
- // function declarations and expressions
- const fnRe = /(\bexport\s+(?:default\s+)?)?\b(?:async\s+)?function\b\s*\*?\s*([A-Za-z_$][\w$]*)?\s*/g;
- while ((m = fnRe.exec(code))) {
- let k = m.index + m[0].length;
- if (code[k] === '<') k = skipGenerics(code, k);
- while (/\s/.test(code[k] ?? '')) k++;
- if (code[k] !== '(') continue;
- add(m[2] ?? '(anonymous)', m.index, k, { exported: !!m[1] });
- }
- // const f = (…) => { f: (…) => { f = async (…) => {
- const arrowRe = /(\bexport\s+)?(?:\b(?:const|let|var)\s+)?([A-Za-z_$][\w$]*)\s*(?::\s*[^=;\n]+)?\s*[=:]\s*(?:async\s+)?(?:<[^>()]*>\s*)?\(/g;
- while ((m = arrowRe.exec(code))) {
- const pOpen = m.index + m[0].length - 1;
- const pClose = matchClose(code, pOpen);
- if (pClose < 0) continue;
- if (!/^\s*(?::\s*[^{;]*?)?=>/.test(code.slice(pClose + 1, pClose + 200)) && !/^\s*:[^;]*=>\s*\{/.test(code.slice(pClose + 1, pClose + 200))) continue;
- if (TS_NOT_NAMES.has(m[2])) continue;
- add(m[2], m.index, pOpen, { exported: !!m[1] });
- }
- // methods: name(…) { at the start of a line
- const methRe = /^[ \t]*((?:(?:public|private|protected|static|async|override|readonly|abstract|get|set)\s+)*)\*?\s*([A-Za-z_$][\w$]*)\s*(?:<[^>()]*>)?\s*\(/gm;
- while ((m = methRe.exec(code))) {
- if (TS_NOT_NAMES.has(m[2])) continue;
- const pOpen = m.index + m[0].length - 1;
- const pClose = matchClose(code, pOpen);
- if (pClose < 0) continue;
- // a call at the start of a line is followed by `;`, `.`, `)` or an operator, never by `{` or `: T {`
- const after = code.slice(pClose + 1, pClose + 300);
- if (!/^\s*(?::[^;=]*?)?\{/.test(after)) continue;
- add(m[2], m.index + m[1].length, pOpen, { hasSelf: inClass(m.index) });
- }
- return { fns, classes };
- }
- function parsePy(src: Source): { fns: Fn[]; classes: Cls[] } {
- const code = src.code;
- const lines = code.split('\n');
- const fns: Fn[] = [];
- const classes: Cls[] = [];
- const indentOf = (s: string) => s.length - s.trimStart().length;
- /** The last line (1-based) of the block opened by line `l` (1-based) at `indent`. */
- const blockEnd = (l: number, indent: number) => {
- let end = l;
- // the signature may span lines: start after the line holding the closing `:`
- for (let k = l; k < lines.length; k++) {
- const t = lines[k];
- if (!t.trim()) continue;
- if (indentOf(t) <= indent) break;
- end = k + 1;
- }
- return end;
- };
- let m: RegExpExecArray | null;
- const cls = /^([ \t]*)class\s+([A-Za-z_]\w*)/gm;
- while ((m = cls.exec(code))) {
- const l = lineOf(src.starts, m.index);
- classes.push({ name: m[2], line: l, endLine: blockEnd(l, m[1].length) });
- }
- const def = /^([ \t]*)(?:async\s+)?def\s+([A-Za-z_]\w*)\s*\(/gm;
- while ((m = def.exec(code))) {
- const pOpen = m.index + m[0].length - 1;
- const pClose = matchClose(code, pOpen);
- if (pClose < 0) continue;
- const colon = code.indexOf(':', code.slice(pClose).search(/\S/) + pClose);
- const sigEndLine = lineOf(src.starts, colon < 0 ? pClose : colon);
- const indent = m[1].length;
- const end = Math.max(sigEndLine, blockEnd(sigEndLine, indent));
- const bodyStart = colon + 1;
- const bodyEnd = end < src.starts.length ? src.starts[end] - 1 : code.length;
- const f = mkFn(src, m[2], m.index + m[1].length, pOpen, pClose, bodyStart - 1, bodyEnd, { indent, exported: indent === 0 && !m[2].startsWith('_') });
- f.endLine = end;
- fns.push(f);
- }
- return { fns, classes };
- }
- function parseRs(src: Source): { fns: Fn[]; classes: Cls[] } {
- const code = src.code;
- const fns: Fn[] = [];
- const classes: Cls[] = [];
- let m: RegExpExecArray | null;
- const traitBlocks: [number, number][] = [];
- const impl = /^[ \t]*(?:unsafe\s+)?impl\b[^{;]*\{/gm;
- while ((m = impl.exec(code))) {
- const open = m.index + m[0].length - 1;
- const close = matchClose(code, open);
- if (close > 0 && /\sfor\s/.test(m[0])) traitBlocks.push([open, close]);
- const name = /impl(?:<[^{]*?>)?\s+([^{]+)/.exec(m[0])?.[1].trim().replace(/\s+/g, ' ') ?? 'impl';
- if (close > 0) classes.push({ name, line: lineOf(src.starts, m.index), endLine: lineOf(src.starts, close) });
- }
- const fn = /(\bpub(?:\s*\([^)]*\))?\s+)?(?:(?:const|async|unsafe|extern(?:\s+"[^"]*")?)\s+)*\bfn\s+([A-Za-z_]\w*)\s*/g;
- while ((m = fn.exec(code))) {
- let k = m.index + m[0].length;
- if (code[k] === '<') k = skipGenerics(code, k);
- while (/\s/.test(code[k] ?? '')) k++;
- if (code[k] !== '(') continue;
- const pClose = matchClose(code, k);
- if (pClose < 0) continue;
- const open = bodyOpen(code, pClose + 1, 'rs');
- if (open < 0) continue;
- const close = matchClose(code, open);
- if (close < 0) continue;
- const traitImpl = traitBlocks.some(([a, b]) => m!.index > a && m!.index < b);
- fns.push(mkFn(src, m[2], m.index, k, pClose, open, close, { exported: !!m[1] && !/\(/.test(m[1]), traitImpl }));
- }
- return { fns, classes };
- }
- /** The body text of a function in masked code, without the outer braces. */
- export function body(src: Source, f: Fn): string {
- return src.code.slice(f.bodyStart, f.bodyEnd);
- }
- /** Import of a project file or module, as written. `spec` is the path or module; `typeOnly` for TS `import type`. */
- export type Import = { spec: string; line: number; typeOnly: boolean; level: number; names: string[]; topLevel: boolean };
- export function imports(src: Source): Import[] {
- const out: Import[] = [];
- const code = src.code;
- if (src.lang === 'ts') {
- for (const s of src.strings) {
- const before = code.slice(Math.max(0, s.start - 400), s.start);
- const m = /(\bimport\s*(type\s+)?[^;'"`]*?\bfrom\s*|\bexport\s*(type\s+)?[^;'"`]*?\bfrom\s*|\bimport\s*\(\s*|\brequire\s*\(\s*|^\s*import\s*)$/.exec(before);
- if (!m) continue;
- const stmtStart = s.start - (before.length - m.index);
- out.push({ spec: s.value, line: s.line, typeOnly: !!(m[2] || m[3]), level: 0, names: [], topLevel: lineStartIndent(src, stmtStart) === 0 });
- }
- } else if (src.lang === 'py') {
- const re = /^([ \t]*)(?:from\s+(\.*)([\w.]*)\s+import\s+([^\n]+)|import\s+([\w., \t]+))/gm;
- let m: RegExpExecArray | null;
- while ((m = re.exec(code))) {
- const line = lineOf(src.starts, m.index);
- const top = m[1].length === 0;
- if (m[5] !== undefined) {
- for (const part of m[5].split(',')) {
- const mod = part.trim().split(/\s+/)[0];
- if (mod) out.push({ spec: mod, line, typeOnly: false, level: 0, names: [], topLevel: top });
- }
- } else {
- let names = m[4];
- if (names.trim().startsWith('(')) {
- const open = m.index + m[0].indexOf('(', m[0].length - names.length);
- const close = matchClose(code, open);
- names = close > 0 ? code.slice(open + 1, close) : names;
- }
- out.push({ spec: m[3], line, typeOnly: false, level: m[2].length, names: names.replace(/[()\\]/g, ' ').split(',').map((x) => x.trim().split(/\s+/)[0]).filter(Boolean), topLevel: top });
- }
- }
- } else {
- const re = /^[ \t]*(?:pub(?:\([^)]*\))?\s+)?use\s+([^;]+);/gm;
- let m: RegExpExecArray | null;
- while ((m = re.exec(code))) out.push({ spec: m[1].replace(/\s+/g, ''), line: lineOf(src.starts, m.index), typeOnly: false, level: 0, names: [], topLevel: true });
- }
- return out;
- }
- function lineStartIndent(src: Source, at: number): number {
- const l = lineOf(src.starts, at);
- const t = src.code.slice(src.starts[l - 1], at);
- return t.trim() === '' ? t.length : -1;
- }
- /** Is this a program entry (a script, a CLI, `main`) rather than library code? */
- export function isEntry(src: Source): boolean {
- if (/(^|\/)(bin|scripts?|examples?|benches)\//.test(src.rel) || /(^|\/)(cli|main|__main__|build)\.[a-z]+$/.test(src.rel)) return true;
- if (src.raw.startsWith('#!')) return true;
- if (src.lang === 'ts') return /\bimport\.meta\.main\b|\brequire\.main\s*===\s*module\b|\bprocess\.argv\b/.test(src.code);
- if (src.lang === 'py') return /^if\s+__name__\s*==/m.test(src.code);
- return /^\s*(?:pub\s+)?(?:async\s+)?fn\s+main\s*\(/m.test(src.code);
- }
- /** The deepest nesting of blocks inside a function body and the line where it is reached.
- * TypeScript: `{` after `)`, `=>`, `else`, `try`, `finally`, `do` opens a block (object literals do not count).
- * Rust: `{` whose statement starts with if/else/while/for/match/loop/unsafe or a closure `|…| {`; match arms
- * `=> {` add no level of their own. Python: indentation of code lines outside brackets. */
- export function nesting(src: Source, f: Fn): { depth: number; line: number } {
- const code = src.code;
- let best = { depth: 0, line: f.line };
- if (src.lang === 'py') {
- const from = lineOf(src.starts, f.bodyStart);
- let base = -1;
- let unit = 0;
- let paren = 0;
- for (let l = from + 1; l <= f.endLine; l++) {
- const a = src.starts[l - 1];
- const b = l < src.starts.length ? src.starts[l] - 1 : code.length;
- const t = code.slice(a, b);
- const startParen = paren;
- for (const c of t) {
- if ('([{'.includes(c)) paren++;
- else if (')]}'.includes(c)) paren = Math.max(0, paren - 1);
- }
- if (!t.trim() || startParen > 0) continue;
- const ind = t.length - t.trimStart().length;
- if (base < 0) base = ind;
- const rel = ind - base;
- if (rel > 0 && (unit === 0 || rel < unit)) unit = rel;
- const depth = unit ? Math.round(rel / unit) : 0;
- if (depth > best.depth) best = { depth, line: l };
- }
- return best;
- }
- const stack: boolean[] = [];
- let depth = 0;
- let segStart = f.bodyStart;
- for (let k = f.bodyStart; k < f.bodyEnd; k++) {
- const c = code[k];
- if (c === '{') {
- const seg = code.slice(segStart, k).trim();
- let block: boolean;
- if (src.lang === 'ts') block = /(\)|=>|\belse|\btry|\bfinally|\bdo)$/.test(seg);
- else block = !/=>$/.test(seg) && (/(^|[\s=(,!])(if|else|while|for|match|loop|unsafe|async)\b/.test(seg) || /\|$/.test(seg) || /\bmove$/.test(seg));
- stack.push(block);
- if (block) {
- depth++;
- if (depth > best.depth) best = { depth, line: lineOf(src.starts, k) };
- }
- segStart = k + 1;
- } else if (c === '}') {
- if (stack.pop()) depth--;
- segStart = k + 1;
- } else if (c === ';') segStart = k + 1;
- }
- return best;
- }