const CLOSING: Record = { '(': ')', '[': ']', '{': '}', '<': '>', }; export function findCalls(source: string, name: string): number[] { const calls: number[] = []; const identifier = new RegExp(`\\b${name}\\b`, 'y'); for (let index = 0; index < source.length; index++) { const skipped = skipStringOrComment(source, index); if (skipped !== undefined) { index = skipped; continue; } identifier.lastIndex = index; if (identifier.test(source)) { calls.push(index); } } return calls; } // Splits the bracketed list that opens at `start` on its top-level commas, so // `(a, f(b, c))` gives `a` and `f(b, c)`. Commas inside nested brackets, // strings and comments don't split, and comments turn into spaces. export function splitTopLevel( text: string, start: number, opening = '([{' ): string[] { const end = findClosingBracket(text, start, opening); const parts: string[] = []; let part = ''; for (let index = start + 1; index < end; index++) { const char = text[index]; const skipped = skipStringOrComment(text, index); if (char === ',') { parts.push(part.trim()); part = ''; } else if (skipped !== undefined) { part += char === '/' ? ' ' : text.slice(index, skipped + 1); index = skipped; } else if (opening.includes(char)) { const closing = findClosingBracket(text, index, opening); part += text.slice(index, closing + 1); index = closing; } else { part += char; } } const last = part.trim(); return last ? [...parts, last] : parts; } export function findClosingBracket( text: string, start: number, opening = '([{' ): number { const expected: string[] = []; for (let index = start; index < text.length; index++) { const char = text[index]; const skipped = skipStringOrComment(text, index); if (skipped !== undefined) { index = skipped; } else if (opening.includes(char)) { expected.push(CLOSING[char]); } else if (char === expected.at(-1)) { expected.pop(); if (expected.length === 0) { return index; } } } throw new Error( `Found no closing bracket for \`${text.slice(start, start + 40)}\`.` ); } export type PreprocessorBlock = { branches: number; hasElse: boolean }; export type PreprocessorMap = { blocks: PreprocessorBlock[]; conditionsAt: (index: number) => string[]; }; export function mapPreprocessorBlocks(source: string): PreprocessorMap { const blocks: PreprocessorBlock[] = []; const ranges: { start: number; conditions: string[] }[] = [ { start: 0, conditions: [] }, ]; const open: { id: number; branch: number }[] = []; const directive = /^[ \t]*#[ \t]*(ifdef|ifndef|if|elif|else|endif)\b.*$/gm; for (const match of source.matchAll(directive)) { const kind = match[1]; if (kind.startsWith('if')) { blocks.push({ branches: 1, hasElse: false }); open.push({ id: blocks.length - 1, branch: 0 }); } else if (open.length > 0) { const current = open.at(-1)!; if (kind === 'endif') { open.pop(); } else { current.branch++; blocks[current.id].branches++; blocks[current.id].hasElse ||= kind === 'else'; } } ranges.push({ start: match.index + match[0].length, conditions: open.map(({ id, branch }) => `${id}:${branch}`), }); } return { blocks, conditionsAt: (index) => ranges.findLast(({ start }) => start <= index)!.conditions, }; } export function hasValueReturn(body: string): boolean { for (let index = 0; index < body.length; index++) { const skipped = skipStringOrComment(body, index); if (skipped !== undefined) { index = skipped; } else if (body[index] === '[' && isLambdaIntroducer(body, index)) { const captureEnd = findClosingBracket(body, index); index = findClosingBracket(body, body.indexOf('{', captureEnd), '{'); } else if (isKeyword(body, index, 'return')) { if (!/^return\s*;/.test(body.slice(index))) { return true; } index += 'return'.length; } } return false; } function isLambdaIntroducer(text: string, bracket: number): boolean { const previous = text.slice(0, bracket).trimEnd().at(-1); return previous === undefined || '(,={;'.includes(previous); } function isKeyword(text: string, index: number, keyword: string): boolean { return ( text.startsWith(keyword, index) && !/\w/.test(text[index - 1] ?? '') && !/\w/.test(text[index + keyword.length] ?? '') ); } function skipStringOrComment(text: string, start: number): number | undefined { const char = text[start]; if (char === "'" && isDigitSeparator(text, start)) { return undefined; } if (char === '"' || char === "'") { return skipString(text, start); } if (text.startsWith('//', start)) { const end = text.indexOf('\n', start); return end === -1 ? text.length : end; } if (text.startsWith('/*', start)) { const end = text.indexOf('*/', start + 2); return end === -1 ? text.length : end + 1; } return undefined; } function isDigitSeparator(text: string, quote: number): boolean { let tokenStart = quote; while (tokenStart > 0 && /[\w']/.test(text[tokenStart - 1])) { tokenStart--; } return ( /[0-9]/.test(text[tokenStart]) && /[0-9a-fA-F]/.test(text[quote + 1] ?? '') ); } function skipString(text: string, start: number): number { const quote = text[start]; for (let index = start + 1; index < text.length; index++) { if (text[index] === '\\') { index++; } else if (text[index] === quote) { return index; } } return text.length; }