ShtukbaseStandard
package file→ .shtukbase/packages/code-lib/checks/lib/lex.ts

checks/lib/lex.ts

312 lines, 9.9 KB.

  1. // A rough, honest lexer for TypeScript/JavaScript, Python and Rust: no parser, no dependencies.
  2. // `mask` returns the source with the contents of comments and strings replaced by spaces (newlines kept, so
  3. // offsets and line numbers stay the same) plus the list of strings and comments it saw. Every heuristic of the
  4. // code-* packages works on the masked text: a brace or a keyword inside a string or a comment never counts.
  5. // Known limits: a JS regex literal is told from division by the token before it; Rust char literals vs
  6. // lifetimes by the next characters; Python f-string expressions are masked like the rest of the string.
  7. export type Lang = 'ts' | 'py' | 'rs';
  8. export type Str = { start: number; end: number; line: number; value: string };
  9. export type Comment = { start: number; end: number; line: number; text: string; block: boolean };
  10. export type Masked = { code: string; strings: Str[]; comments: Comment[] };
  11. export function langOf(path: string): Lang | null {
  12. const m = /\.([A-Za-z0-9]+)$/.exec(path);
  13. const ext = m ? m[1].toLowerCase() : '';
  14. if (['ts', 'tsx', 'mts', 'cts', 'js', 'jsx', 'mjs', 'cjs'].includes(ext)) return 'ts';
  15. if (ext === 'py' || ext === 'pyi') return 'py';
  16. if (ext === 'rs') return 'rs';
  17. return null;
  18. }
  19. const REGEX_BEFORE = new Set('(,=:[!&|?{};+-*%<>~^'.split(''));
  20. const REGEX_KEYWORDS = /\b(return|typeof|case|do|else|in|of|new|delete|void|throw|yield|await)\s*$/;
  21. export function mask(src: string, lang: Lang): Masked {
  22. const out = src.split('');
  23. const strings: Str[] = [];
  24. const comments: Comment[] = [];
  25. const n = src.length;
  26. const blank = (a: number, b: number) => {
  27. for (let k = a; k < b; k++) if (out[k] !== '\n') out[k] = ' ';
  28. };
  29. const addStr = (qStart: number, cStart: number, cEnd: number, qEnd: number) => {
  30. strings.push({ start: qStart, end: qEnd, line: 0, value: src.slice(cStart, cEnd) });
  31. blank(cStart, cEnd);
  32. };
  33. const addComment = (a: number, b: number, block: boolean) => {
  34. comments.push({ start: a, end: b, line: 0, text: src.slice(a, b), block });
  35. blank(a, b);
  36. };
  37. /** End of a simple quoted string starting at the quote `i`; stops at a newline when `oneLine`. */
  38. const quoted = (i: number, q: string, oneLine: boolean, escapes = true): number => {
  39. let k = i + 1;
  40. while (k < n) {
  41. const c = src[k];
  42. if (escapes && c === '\\') { k += 2; continue; }
  43. if (c === q) return k;
  44. if (oneLine && c === '\n') return k - 1;
  45. k++;
  46. }
  47. return n - 1;
  48. };
  49. /** The last significant (non-space) char of the masked output before `i`. */
  50. const prevSig = (i: number): number => {
  51. let k = i - 1;
  52. while (k >= 0 && /\s/.test(out[k])) k--;
  53. return k;
  54. };
  55. // TypeScript template literal with ${} nesting: returns the index of the closing backtick.
  56. const template = (i: number): number => {
  57. let k = i + 1;
  58. let segStart = k;
  59. let value = '';
  60. while (k < n) {
  61. const c = src[k];
  62. if (c === '\\') { k += 2; continue; }
  63. if (c === '`') {
  64. value += src.slice(segStart, k);
  65. blank(segStart, k);
  66. strings.push({ start: i, end: k, line: 0, value });
  67. return k;
  68. }
  69. if (c === '$' && src[k + 1] === '{') {
  70. value += src.slice(segStart, k) + '${…}';
  71. blank(segStart, k);
  72. k = tsCode(k + 2, true); // returns index of the closing }
  73. segStart = k + 1;
  74. k++;
  75. continue;
  76. }
  77. k++;
  78. }
  79. blank(segStart, n);
  80. return n - 1;
  81. };
  82. // TypeScript code from `start`; when `nested`, stops at the } that closes a template expression.
  83. const tsCode = (start: number, nested: boolean): number => {
  84. let depth = 0;
  85. let i = start;
  86. while (i < n) {
  87. const c = src[i];
  88. const d = src[i + 1];
  89. if (c === '/' && d === '/') {
  90. let e = src.indexOf('\n', i);
  91. if (e < 0) e = n;
  92. addComment(i, e, false);
  93. i = e;
  94. continue;
  95. }
  96. if (c === '/' && d === '*') {
  97. let e = src.indexOf('*/', i + 2);
  98. e = e < 0 ? n : e + 2;
  99. addComment(i, e, true);
  100. i = e;
  101. continue;
  102. }
  103. if (c === "'" || c === '"') {
  104. const e = quoted(i, c, true);
  105. addStr(i, i + 1, e, e);
  106. i = e + 1;
  107. continue;
  108. }
  109. if (c === '`') {
  110. i = template(i) + 1;
  111. continue;
  112. }
  113. if (c === '/') {
  114. const p = prevSig(i);
  115. const before = src.slice(Math.max(0, i - 12), i);
  116. const pc = p >= 0 ? out[p] : '';
  117. if (p < 0 || REGEX_BEFORE.has(pc) || REGEX_KEYWORDS.test(before)) {
  118. // a regex literal: up to the unescaped / outside a [class]
  119. let k = i + 1;
  120. let cls = false;
  121. while (k < n && src[k] !== '\n') {
  122. const ch = src[k];
  123. if (ch === '\\') { k += 2; continue; }
  124. if (ch === '[') cls = true;
  125. else if (ch === ']') cls = false;
  126. else if (ch === '/' && !cls) break;
  127. k++;
  128. }
  129. if (k < n && src[k] === '/') {
  130. addStr(i, i + 1, k, k);
  131. i = k + 1;
  132. while (i < n && /[a-z]/.test(src[i])) i++;
  133. continue;
  134. }
  135. }
  136. i++;
  137. continue;
  138. }
  139. if (nested) {
  140. if (c === '{') depth++;
  141. else if (c === '}') {
  142. if (depth === 0) return i;
  143. depth--;
  144. }
  145. }
  146. i++;
  147. }
  148. return n;
  149. };
  150. const pyCode = () => {
  151. let i = 0;
  152. while (i < n) {
  153. const c = src[i];
  154. if (c === '#') {
  155. let e = src.indexOf('\n', i);
  156. if (e < 0) e = n;
  157. addComment(i, e, false);
  158. i = e;
  159. continue;
  160. }
  161. if (c === "'" || c === '"') {
  162. // prefix letters (r, b, f, u) stay in the code; a raw string still ends at an unescaped quote
  163. const triple = src.slice(i, i + 3) === c.repeat(3);
  164. if (triple) {
  165. let k = i + 3;
  166. while (k < n) {
  167. if (src[k] === '\\') { k += 2; continue; }
  168. if (src.slice(k, k + 3) === c.repeat(3)) break;
  169. k++;
  170. }
  171. const e = Math.min(k, n);
  172. addStr(i, i + 3, e, e + 2);
  173. i = e + 3;
  174. continue;
  175. }
  176. const e = quoted(i, c, true, true);
  177. addStr(i, i + 1, e, e);
  178. i = e + 1;
  179. continue;
  180. }
  181. i++;
  182. }
  183. };
  184. const rsCode = () => {
  185. let i = 0;
  186. while (i < n) {
  187. const c = src[i];
  188. const d = src[i + 1];
  189. if (c === '/' && d === '/') {
  190. let e = src.indexOf('\n', i);
  191. if (e < 0) e = n;
  192. addComment(i, e, false);
  193. i = e;
  194. continue;
  195. }
  196. if (c === '/' && d === '*') {
  197. let k = i + 2;
  198. let depth = 1;
  199. while (k < n && depth > 0) {
  200. if (src[k] === '/' && src[k + 1] === '*') { depth++; k += 2; continue; }
  201. if (src[k] === '*' && src[k + 1] === '/') { depth--; k += 2; continue; }
  202. k++;
  203. }
  204. addComment(i, k, true);
  205. i = k;
  206. continue;
  207. }
  208. // raw strings: r"..", r#".."#, br#".."#
  209. const raw = /^b?r(#*)"/.exec(src.slice(i, i + 40));
  210. if (raw && !/[A-Za-z0-9_]/.test(src[i - 1] ?? '')) {
  211. const hashes = raw[1];
  212. const open = i + raw[0].length;
  213. const close = src.indexOf('"' + hashes, open);
  214. const e = close < 0 ? n : close;
  215. addStr(i, open, e, e + hashes.length);
  216. i = e + 1 + hashes.length;
  217. continue;
  218. }
  219. if (c === '"') {
  220. const e = quoted(i, '"', false);
  221. addStr(i, i + 1, e, e);
  222. i = e + 1;
  223. continue;
  224. }
  225. if (c === "'") {
  226. // char literal or lifetime
  227. if (d === '\\') {
  228. const e = src.indexOf("'", i + 3);
  229. if (e > 0 && e - i < 12) { addStr(i, i + 1, e, e); i = e + 1; continue; }
  230. } else {
  231. const cp = src.codePointAt(i + 1) ?? 0;
  232. const w = cp > 0xffff ? 2 : 1;
  233. if (src[i + 1 + w] === "'") { addStr(i, i + 1, i + 1 + w, i + 1 + w); i = i + 2 + w; continue; }
  234. }
  235. i++;
  236. continue;
  237. }
  238. i++;
  239. }
  240. };
  241. if (lang === 'ts') tsCode(0, false);
  242. else if (lang === 'py') pyCode();
  243. else rsCode();
  244. let code = out.join('');
  245. if (lang === 'rs') code = dropRustTests(code);
  246. strings.sort((a, b) => a.start - b.start);
  247. comments.sort((a, b) => a.start - b.start);
  248. const starts = lineStarts(src);
  249. for (const x of [...strings, ...comments]) x.line = lineOf(starts, x.start);
  250. return { code, strings, comments };
  251. }
  252. /** Blanks `#[cfg(test)] mod x { ... }` blocks: unit tests inside a Rust file are not the code the norms judge. */
  253. function dropRustTests(code: string): string {
  254. const re = /#\[cfg\(test\)\]\s*(?:pub(?:\([^)]*\))?\s+)?mod\s+\w+\s*\{/g;
  255. let m: RegExpExecArray | null;
  256. let out = code;
  257. while ((m = re.exec(code))) {
  258. const open = m.index + m[0].length - 1;
  259. const close = matchClose(code, open);
  260. if (close < 0) continue;
  261. out = out.slice(0, m.index) + out.slice(m.index, close + 1).replace(/[^\n]/g, ' ') + out.slice(close + 1);
  262. re.lastIndex = close + 1;
  263. }
  264. return out;
  265. }
  266. const PAIRS: Record<string, string> = { '(': ')', '[': ']', '{': '}' };
  267. /** The index of the bracket that closes the one at `open` in masked code; -1 when it is not closed. */
  268. export function matchClose(code: string, open: number): number {
  269. const o = code[open];
  270. const c = PAIRS[o];
  271. if (!c) return -1;
  272. let depth = 0;
  273. for (let k = open; k < code.length; k++) {
  274. const ch = code[k];
  275. if (ch === o) depth++;
  276. else if (ch === c) {
  277. depth--;
  278. if (depth === 0) return k;
  279. }
  280. }
  281. return -1;
  282. }
  283. /** Offsets of line starts, for turning an offset into a 1-based line number. */
  284. export function lineStarts(text: string): number[] {
  285. const s = [0];
  286. for (let k = 0; k < text.length; k++) if (text[k] === '\n') s.push(k + 1);
  287. return s;
  288. }
  289. export function lineOf(starts: number[], offset: number): number {
  290. let lo = 0;
  291. let hi = starts.length - 1;
  292. while (lo < hi) {
  293. const mid = (lo + hi + 1) >> 1;
  294. if (starts[mid] <= offset) lo = mid;
  295. else hi = mid - 1;
  296. }
  297. return lo + 1;
  298. }