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

Function flattenMidStatementConditionals

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

Source from the content-addressed store, hash-verified

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

Callers 2

preParseCppSourceFunction · 0.85

Calls 4

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

Tested by

no test coverage detected