MCPcopy Create free account
hub / github.com/colbymchenry/codegraph / flattenMidStatementConditionals

Function flattenMidStatementConditionals

src/extraction/languages/c-cpp.ts:1793–1860  ·  view source on GitHub ↗
(source: string)

Source from the content-addressed store, hash-verified

1791 * kept. A conditional between whole declarations is left alone.
1792 */
1793export function flattenMidStatementConditionals(source: string): string {
1794 if (!source.includes('#')) return source;
1795 const lines = source.split('\n');
1796 const directive = (i: number) => /^[ \t]*#[ \t]*(\w+)/.exec(lines[i] ?? '')?.[1] ?? null;
1797 const code = (i: number) => (lines[i] ?? '').replace(/\/\/.*$/, '').replace(/\/\*.*?\*\//g, '').trim();
1798 let changed = false;
1799 const blank = (i: number) => {
1800 lines[i] = (lines[i] ?? '').replace(/[^\r]/g, ' ');
1801 changed = true;
1802 };
1803 let lastCode = ''; // the last non-directive code line, trimmed
1804 let inBlockComment = false;
1805 let region = 0; // #if depth inside a flattened conditional (0 = none)
1806 let skipFrom = 0; // the depth whose later branches are blanked (0 = none)
1807 let continued = false; // inside a `\`-continued directive (a multi-line #define)
1808 for (let i = 0; i < lines.length; i++) {
1809 if (continued) {
1810 continued = /\\\s*$/.test(lines[i] ?? '');
1811 continue;
1812 }
1813 const d = directive(i);
1814 if (d !== null && !inBlockComment) {
1815 // A directive continued with `\` spans lines; its body is not code.
1816 if (/\\\s*$/.test(lines[i]!)) {
1817 continued = true;
1818 if (region === 0) continue;
1819 }
1820 const opens = /^if/.test(d);
1821 if (region === 0) {
1822 // Not after a statement macro written without its `;`
1823 // (`RAPIDJSON_DIAG_OFF(padded)`), either.
1824 const mid = opens && lastCode !== '' && !/[;{}]$|^[\w\s]*:$|\*\/$/.test(lastCode) &&
1825 !/^(?:public|private|protected)\s*:$/.test(lastCode) && !/^[A-Z][A-Z0-9_]*(?:\s*\(.*\))?$/.test(lastCode);
1826 if (!mid) continue;
1827 region = 1;
1828 blank(i);
1829 continue;
1830 }
1831 if (opens) region++;
1832 else if ((d === 'else' || d === 'elif') && skipFrom === 0) skipFrom = region;
1833 else if (d === 'endif') {
1834 if (skipFrom === region) skipFrom = 0;
1835 region--;
1836 }
1837 if (/^(?:if|ifdef|ifndef|else|elif|elifdef|elifndef|endif)$/.test(d)) blank(i);
1838 continue;
1839 }
1840 const text = lines[i] ?? '';
1841 if (region > 0 && skipFrom > 0) {
1842 if (text.trim() !== '') blank(i);
1843 continue;
1844 }
1845 // Track block comments so a `#` or `;` inside one is not read as code.
1846 const trimmed = code(i);
1847 if (inBlockComment) {
1848 if (text.includes('*/')) inBlockComment = false;
1849 continue;
1850 }

Callers 2

preParseCppSourceFunction · 0.85

Calls 4

directiveFunction · 0.70
blankFunction · 0.70
codeFunction · 0.70
joinMethod · 0.45

Tested by

no test coverage detected