ShtukbaseStandard
файл пакета→ .shtukbase/packages/code-lib/checks/lib/units.ts

checks/lib/units.ts

404 строки, 17.1 КБ.

Файл как есть в пакете: код и комментарии в нём не переводятся.

  1. // Functions, classes and imports found in masked code by regular expressions and bracket matching.
  2. // Rough on purpose: no parser. What it finds:
  3. // TypeScript/JavaScript — `function f(`, `const f = (…) => {`, `f: (…) => {`, `f = async (…) => {`, class and object
  4. // methods `f(…) {` at the start of a line; anonymous callbacks are part of the function around them.
  5. // Python — `def f(` with its indented body; `class X`.
  6. // Rust — `fn f(` with a body (trait declarations without a body are skipped); `impl … {` blocks as classes.
  7. import { type Lang, lineOf, matchClose } from './lex.ts';
  8. import type { Source } from './scan.ts';
  9. export type Fn = {
  10. name: string;
  11. line: number; // line of the signature
  12. endLine: number;
  13. params: string[]; // parameter names ('' for a destructured or unnamed one); self/this/cls dropped
  14. paramText: string[]; // the raw parameter text, one per parameter
  15. hasSelf: boolean; // a method: Rust `self`, Python `self`/`cls`, TypeScript method inside a class
  16. exported: boolean;
  17. bodyStart: number; // offset of the first char inside the body
  18. bodyEnd: number; // offset of the closing } (TypeScript, Rust) or of the end of the body (Python)
  19. indent: number; // Python: the indent of `def`
  20. traitImpl: boolean; // Rust: inside `impl Trait for Type`, where the signature is the trait's, not the author's
  21. };
  22. export type Cls = { name: string; line: number; endLine: number };
  23. 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_']);
  24. /** Splits a parameter list at top-level commas. `=>` and `->` do not close an angle bracket. */
  25. export function splitTop(text: string): string[] {
  26. const out: string[] = [];
  27. let depth = 0;
  28. let cur = '';
  29. for (let k = 0; k < text.length; k++) {
  30. const c = text[k];
  31. if ('([{<'.includes(c)) depth++;
  32. else if (')]}'.includes(c)) depth--;
  33. else if (c === '>' && text[k - 1] !== '=' && text[k - 1] !== '-') depth--;
  34. if (c === ',' && depth <= 0) {
  35. out.push(cur);
  36. cur = '';
  37. depth = 0;
  38. continue;
  39. }
  40. cur += c;
  41. }
  42. out.push(cur);
  43. return out.map((x) => x.trim()).filter(Boolean);
  44. }
  45. function paramName(p: string, lang: Lang): string {
  46. let s = p.replace(/^\.\.\.|^\*{1,2}/, '').trim();
  47. if (lang === 'ts') s = s.replace(/^(public|private|protected|readonly|override)\s+/g, '');
  48. if (lang === 'rs') s = s.replace(/^mut\s+/, '');
  49. const m = /^([A-Za-z_$][\w$]*)/.exec(s);
  50. return m ? m[1] : '';
  51. }
  52. /** Skips a type annotation after `)`: returns the offset of the body `{`, or -1 for no body (`;`, `=>` expr, end). */
  53. function bodyOpen(code: string, from: number, lang: Lang): number {
  54. let k = from;
  55. let depth = 0;
  56. while (k < code.length) {
  57. const c = code[k];
  58. if (depth === 0) {
  59. if (c === '{') {
  60. // a TypeScript object type literal right after `:` is part of the type
  61. const before = code.slice(from, k).trim();
  62. if (lang === 'ts' && /:$|[|&<,]$/.test(before)) {
  63. const e = matchClose(code, k);
  64. if (e < 0) return -1;
  65. k = e + 1;
  66. continue;
  67. }
  68. return k;
  69. }
  70. if (c === ';' || c === '}') return -1;
  71. if (lang === 'ts' && c === '=' && code[k + 1] === '>') {
  72. let j = k + 2;
  73. while (/\s/.test(code[j] ?? '')) j++;
  74. return code[j] === '{' ? j : -1;
  75. }
  76. if (lang === 'ts' && c === '\n') {
  77. // a method signature in an interface or an overload ends at the line end
  78. const rest = code.slice(from, k).trim();
  79. if (rest === '' || rest.startsWith(':')) { k++; continue; }
  80. }
  81. }
  82. if ('([<'.includes(c)) depth++;
  83. else if (')]'.includes(c)) depth--;
  84. else if (c === '>' && code[k - 1] !== '=' && code[k - 1] !== '-') depth = Math.max(0, depth - 1);
  85. k++;
  86. }
  87. return -1;
  88. }
  89. /** Skips `<…>` generics starting at `k` (which must be `<`); returns the offset after it. */
  90. function skipGenerics(code: string, k: number): number {
  91. let depth = 0;
  92. for (; k < code.length; k++) {
  93. if (code[k] === '<') depth++;
  94. else if (code[k] === '>' && code[k - 1] !== '-' && code[k - 1] !== '=') {
  95. depth--;
  96. if (depth === 0) return k + 1;
  97. } else if (code[k] === '{' || code[k] === ';') return k;
  98. }
  99. return k;
  100. }
  101. const cache = new WeakMap<Source, { fns: Fn[]; classes: Cls[] }>();
  102. export function functions(src: Source): Fn[] {
  103. return parse(src).fns;
  104. }
  105. export function classes(src: Source): Cls[] {
  106. return parse(src).classes;
  107. }
  108. function parse(src: Source): { fns: Fn[]; classes: Cls[] } {
  109. const hit = cache.get(src);
  110. if (hit) return hit;
  111. const res = src.lang === 'py' ? parsePy(src) : src.lang === 'rs' ? parseRs(src) : parseTs(src);
  112. res.fns.sort((a, b) => a.bodyStart - b.bodyStart);
  113. cache.set(src, res);
  114. return res;
  115. }
  116. function mkFn(src: Source, name: string, sigAt: number, pOpen: number, pClose: number, open: number, close: number, extra: Partial<Fn>): Fn {
  117. const parts = splitTop(src.code.slice(pOpen + 1, pClose));
  118. const raw = parts;
  119. let hasSelf = !!extra.hasSelf;
  120. const keep: string[] = [];
  121. const keepText: string[] = [];
  122. for (const p of raw) {
  123. const t = p.trim();
  124. if (src.lang === 'rs' && /^(&\s*('\w+\s+)?(mut\s+)?)?(mut\s+)?self\b/.test(t)) { hasSelf = true; continue; }
  125. if (src.lang === 'py' && /^(self|cls)\b/.test(t) && keep.length === 0 && keepText.length === 0) { hasSelf = true; continue; }
  126. if (src.lang === 'py' && (t === '*' || t === '/')) continue;
  127. if (src.lang === 'ts' && /^this\s*:/.test(t)) continue;
  128. keep.push(paramName(t, src.lang));
  129. keepText.push(t);
  130. }
  131. return {
  132. name,
  133. line: lineOf(src.starts, sigAt),
  134. endLine: lineOf(src.starts, close),
  135. params: keep,
  136. paramText: keepText,
  137. hasSelf,
  138. exported: !!extra.exported,
  139. bodyStart: open + 1,
  140. bodyEnd: close,
  141. indent: extra.indent ?? 0,
  142. traitImpl: !!extra.traitImpl,
  143. };
  144. }
  145. function parseTs(src: Source): { fns: Fn[]; classes: Cls[] } {
  146. const code = src.code;
  147. const fns: Fn[] = [];
  148. const classes: Cls[] = [];
  149. const seen = new Set<number>();
  150. const add = (name: string, sigAt: number, pOpen: number, extra: Partial<Fn>) => {
  151. if (seen.has(pOpen)) return;
  152. const pClose = matchClose(code, pOpen);
  153. if (pClose < 0) return;
  154. const open = bodyOpen(code, pClose + 1, 'ts');
  155. if (open < 0) return;
  156. const close = matchClose(code, open);
  157. if (close < 0) return;
  158. seen.add(pOpen);
  159. fns.push(mkFn(src, name, sigAt, pOpen, pClose, open, close, extra));
  160. };
  161. let m: RegExpExecArray | null;
  162. const cls = /^[ \t]*(?:export\s+)?(?:default\s+)?(?:abstract\s+)?class\s+([A-Za-z_$][\w$]*)[^{]*\{/gm;
  163. while ((m = cls.exec(code))) {
  164. const open = m.index + m[0].length - 1;
  165. const close = matchClose(code, open);
  166. if (close > 0) classes.push({ name: m[1], line: lineOf(src.starts, m.index), endLine: lineOf(src.starts, close) });
  167. }
  168. const inClass = (at: number) => classes.some((c) => lineOf(src.starts, at) > c.line && lineOf(src.starts, at) <= c.endLine);
  169. // function declarations and expressions
  170. const fnRe = /(\bexport\s+(?:default\s+)?)?\b(?:async\s+)?function\b\s*\*?\s*([A-Za-z_$][\w$]*)?\s*/g;
  171. while ((m = fnRe.exec(code))) {
  172. let k = m.index + m[0].length;
  173. if (code[k] === '<') k = skipGenerics(code, k);
  174. while (/\s/.test(code[k] ?? '')) k++;
  175. if (code[k] !== '(') continue;
  176. add(m[2] ?? '(anonymous)', m.index, k, { exported: !!m[1] });
  177. }
  178. // const f = (…) => { f: (…) => { f = async (…) => {
  179. const arrowRe = /(\bexport\s+)?(?:\b(?:const|let|var)\s+)?([A-Za-z_$][\w$]*)\s*(?::\s*[^=;\n]+)?\s*[=:]\s*(?:async\s+)?(?:<[^>()]*>\s*)?\(/g;
  180. while ((m = arrowRe.exec(code))) {
  181. const pOpen = m.index + m[0].length - 1;
  182. const pClose = matchClose(code, pOpen);
  183. if (pClose < 0) continue;
  184. if (!/^\s*(?::\s*[^{;]*?)?=>/.test(code.slice(pClose + 1, pClose + 200)) && !/^\s*:[^;]*=>\s*\{/.test(code.slice(pClose + 1, pClose + 200))) continue;
  185. if (TS_NOT_NAMES.has(m[2])) continue;
  186. add(m[2], m.index, pOpen, { exported: !!m[1] });
  187. }
  188. // methods: name(…) { at the start of a line
  189. const methRe = /^[ \t]*((?:(?:public|private|protected|static|async|override|readonly|abstract|get|set)\s+)*)\*?\s*([A-Za-z_$][\w$]*)\s*(?:<[^>()]*>)?\s*\(/gm;
  190. while ((m = methRe.exec(code))) {
  191. if (TS_NOT_NAMES.has(m[2])) continue;
  192. const pOpen = m.index + m[0].length - 1;
  193. const pClose = matchClose(code, pOpen);
  194. if (pClose < 0) continue;
  195. // a call at the start of a line is followed by `;`, `.`, `)` or an operator, never by `{` or `: T {`
  196. const after = code.slice(pClose + 1, pClose + 300);
  197. if (!/^\s*(?::[^;=]*?)?\{/.test(after)) continue;
  198. add(m[2], m.index + m[1].length, pOpen, { hasSelf: inClass(m.index) });
  199. }
  200. return { fns, classes };
  201. }
  202. function parsePy(src: Source): { fns: Fn[]; classes: Cls[] } {
  203. const code = src.code;
  204. const lines = code.split('\n');
  205. const fns: Fn[] = [];
  206. const classes: Cls[] = [];
  207. const indentOf = (s: string) => s.length - s.trimStart().length;
  208. /** The last line (1-based) of the block opened by line `l` (1-based) at `indent`. */
  209. const blockEnd = (l: number, indent: number) => {
  210. let end = l;
  211. // the signature may span lines: start after the line holding the closing `:`
  212. for (let k = l; k < lines.length; k++) {
  213. const t = lines[k];
  214. if (!t.trim()) continue;
  215. if (indentOf(t) <= indent) break;
  216. end = k + 1;
  217. }
  218. return end;
  219. };
  220. let m: RegExpExecArray | null;
  221. const cls = /^([ \t]*)class\s+([A-Za-z_]\w*)/gm;
  222. while ((m = cls.exec(code))) {
  223. const l = lineOf(src.starts, m.index);
  224. classes.push({ name: m[2], line: l, endLine: blockEnd(l, m[1].length) });
  225. }
  226. const def = /^([ \t]*)(?:async\s+)?def\s+([A-Za-z_]\w*)\s*\(/gm;
  227. while ((m = def.exec(code))) {
  228. const pOpen = m.index + m[0].length - 1;
  229. const pClose = matchClose(code, pOpen);
  230. if (pClose < 0) continue;
  231. const colon = code.indexOf(':', code.slice(pClose).search(/\S/) + pClose);
  232. const sigEndLine = lineOf(src.starts, colon < 0 ? pClose : colon);
  233. const indent = m[1].length;
  234. const end = Math.max(sigEndLine, blockEnd(sigEndLine, indent));
  235. const bodyStart = colon + 1;
  236. const bodyEnd = end < src.starts.length ? src.starts[end] - 1 : code.length;
  237. const f = mkFn(src, m[2], m.index + m[1].length, pOpen, pClose, bodyStart - 1, bodyEnd, { indent, exported: indent === 0 && !m[2].startsWith('_') });
  238. f.endLine = end;
  239. fns.push(f);
  240. }
  241. return { fns, classes };
  242. }
  243. function parseRs(src: Source): { fns: Fn[]; classes: Cls[] } {
  244. const code = src.code;
  245. const fns: Fn[] = [];
  246. const classes: Cls[] = [];
  247. let m: RegExpExecArray | null;
  248. const traitBlocks: [number, number][] = [];
  249. const impl = /^[ \t]*(?:unsafe\s+)?impl\b[^{;]*\{/gm;
  250. while ((m = impl.exec(code))) {
  251. const open = m.index + m[0].length - 1;
  252. const close = matchClose(code, open);
  253. if (close > 0 && /\sfor\s/.test(m[0])) traitBlocks.push([open, close]);
  254. const name = /impl(?:<[^{]*?>)?\s+([^{]+)/.exec(m[0])?.[1].trim().replace(/\s+/g, ' ') ?? 'impl';
  255. if (close > 0) classes.push({ name, line: lineOf(src.starts, m.index), endLine: lineOf(src.starts, close) });
  256. }
  257. const fn = /(\bpub(?:\s*\([^)]*\))?\s+)?(?:(?:const|async|unsafe|extern(?:\s+"[^"]*")?)\s+)*\bfn\s+([A-Za-z_]\w*)\s*/g;
  258. while ((m = fn.exec(code))) {
  259. let k = m.index + m[0].length;
  260. if (code[k] === '<') k = skipGenerics(code, k);
  261. while (/\s/.test(code[k] ?? '')) k++;
  262. if (code[k] !== '(') continue;
  263. const pClose = matchClose(code, k);
  264. if (pClose < 0) continue;
  265. const open = bodyOpen(code, pClose + 1, 'rs');
  266. if (open < 0) continue;
  267. const close = matchClose(code, open);
  268. if (close < 0) continue;
  269. const traitImpl = traitBlocks.some(([a, b]) => m!.index > a && m!.index < b);
  270. fns.push(mkFn(src, m[2], m.index, k, pClose, open, close, { exported: !!m[1] && !/\(/.test(m[1]), traitImpl }));
  271. }
  272. return { fns, classes };
  273. }
  274. /** The body text of a function in masked code, without the outer braces. */
  275. export function body(src: Source, f: Fn): string {
  276. return src.code.slice(f.bodyStart, f.bodyEnd);
  277. }
  278. /** Import of a project file or module, as written. `spec` is the path or module; `typeOnly` for TS `import type`. */
  279. export type Import = { spec: string; line: number; typeOnly: boolean; level: number; names: string[]; topLevel: boolean };
  280. export function imports(src: Source): Import[] {
  281. const out: Import[] = [];
  282. const code = src.code;
  283. if (src.lang === 'ts') {
  284. for (const s of src.strings) {
  285. const before = code.slice(Math.max(0, s.start - 400), s.start);
  286. 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);
  287. if (!m) continue;
  288. const stmtStart = s.start - (before.length - m.index);
  289. out.push({ spec: s.value, line: s.line, typeOnly: !!(m[2] || m[3]), level: 0, names: [], topLevel: lineStartIndent(src, stmtStart) === 0 });
  290. }
  291. } else if (src.lang === 'py') {
  292. const re = /^([ \t]*)(?:from\s+(\.*)([\w.]*)\s+import\s+([^\n]+)|import\s+([\w., \t]+))/gm;
  293. let m: RegExpExecArray | null;
  294. while ((m = re.exec(code))) {
  295. const line = lineOf(src.starts, m.index);
  296. const top = m[1].length === 0;
  297. if (m[5] !== undefined) {
  298. for (const part of m[5].split(',')) {
  299. const mod = part.trim().split(/\s+/)[0];
  300. if (mod) out.push({ spec: mod, line, typeOnly: false, level: 0, names: [], topLevel: top });
  301. }
  302. } else {
  303. let names = m[4];
  304. if (names.trim().startsWith('(')) {
  305. const open = m.index + m[0].indexOf('(', m[0].length - names.length);
  306. const close = matchClose(code, open);
  307. names = close > 0 ? code.slice(open + 1, close) : names;
  308. }
  309. 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 });
  310. }
  311. }
  312. } else {
  313. const re = /^[ \t]*(?:pub(?:\([^)]*\))?\s+)?use\s+([^;]+);/gm;
  314. let m: RegExpExecArray | null;
  315. 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 });
  316. }
  317. return out;
  318. }
  319. function lineStartIndent(src: Source, at: number): number {
  320. const l = lineOf(src.starts, at);
  321. const t = src.code.slice(src.starts[l - 1], at);
  322. return t.trim() === '' ? t.length : -1;
  323. }
  324. /** Is this a program entry (a script, a CLI, `main`) rather than library code? */
  325. export function isEntry(src: Source): boolean {
  326. if (/(^|\/)(bin|scripts?|examples?|benches)\//.test(src.rel) || /(^|\/)(cli|main|__main__|build)\.[a-z]+$/.test(src.rel)) return true;
  327. if (src.raw.startsWith('#!')) return true;
  328. if (src.lang === 'ts') return /\bimport\.meta\.main\b|\brequire\.main\s*===\s*module\b|\bprocess\.argv\b/.test(src.code);
  329. if (src.lang === 'py') return /^if\s+__name__\s*==/m.test(src.code);
  330. return /^\s*(?:pub\s+)?(?:async\s+)?fn\s+main\s*\(/m.test(src.code);
  331. }
  332. /** The deepest nesting of blocks inside a function body and the line where it is reached.
  333. * TypeScript: `{` after `)`, `=>`, `else`, `try`, `finally`, `do` opens a block (object literals do not count).
  334. * Rust: `{` whose statement starts with if/else/while/for/match/loop/unsafe or a closure `|…| {`; match arms
  335. * `=> {` add no level of their own. Python: indentation of code lines outside brackets. */
  336. export function nesting(src: Source, f: Fn): { depth: number; line: number } {
  337. const code = src.code;
  338. let best = { depth: 0, line: f.line };
  339. if (src.lang === 'py') {
  340. const from = lineOf(src.starts, f.bodyStart);
  341. let base = -1;
  342. let unit = 0;
  343. let paren = 0;
  344. for (let l = from + 1; l <= f.endLine; l++) {
  345. const a = src.starts[l - 1];
  346. const b = l < src.starts.length ? src.starts[l] - 1 : code.length;
  347. const t = code.slice(a, b);
  348. const startParen = paren;
  349. for (const c of t) {
  350. if ('([{'.includes(c)) paren++;
  351. else if (')]}'.includes(c)) paren = Math.max(0, paren - 1);
  352. }
  353. if (!t.trim() || startParen > 0) continue;
  354. const ind = t.length - t.trimStart().length;
  355. if (base < 0) base = ind;
  356. const rel = ind - base;
  357. if (rel > 0 && (unit === 0 || rel < unit)) unit = rel;
  358. const depth = unit ? Math.round(rel / unit) : 0;
  359. if (depth > best.depth) best = { depth, line: l };
  360. }
  361. return best;
  362. }
  363. const stack: boolean[] = [];
  364. let depth = 0;
  365. let segStart = f.bodyStart;
  366. for (let k = f.bodyStart; k < f.bodyEnd; k++) {
  367. const c = code[k];
  368. if (c === '{') {
  369. const seg = code.slice(segStart, k).trim();
  370. let block: boolean;
  371. if (src.lang === 'ts') block = /(\)|=>|\belse|\btry|\bfinally|\bdo)$/.test(seg);
  372. else block = !/=>$/.test(seg) && (/(^|[\s=(,!])(if|else|while|for|match|loop|unsafe|async)\b/.test(seg) || /\|$/.test(seg) || /\bmove$/.test(seg));
  373. stack.push(block);
  374. if (block) {
  375. depth++;
  376. if (depth > best.depth) best = { depth, line: lineOf(src.starts, k) };
  377. }
  378. segStart = k + 1;
  379. } else if (c === '}') {
  380. if (stack.pop()) depth--;
  381. segStart = k + 1;
  382. } else if (c === ';') segStart = k + 1;
  383. }
  384. return best;
  385. }