Skip to content

Commit

Permalink
Merge pull request #25 from davepagurek/fix/traverse-replaced
Browse files Browse the repository at this point in the history
Only traverse replaced node after calling .replace()
  • Loading branch information
AndrewRayCode authored May 30, 2024
2 parents d298958 + 841231a commit 9c1c4a9
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 3 deletions.
10 changes: 7 additions & 3 deletions src/ast/visit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -115,19 +115,23 @@ export const visit = (ast: Program | AstNode, visitors: NodeVisitors) => {
}
}

Object.entries(node)
const toTraverse = (path.replaced as AstNode | undefined) ?? node;
const newPath = path.replaced
? makePath(toTraverse, parent, parentPath, key, index)
: path;
Object.entries(toTraverse)
.filter(([_, nodeValue]) => isTraversable(nodeValue))
.forEach(([nodeKey, nodeValue]) => {
if (Array.isArray(nodeValue)) {
for (let i = 0, offset = 0; i - offset < nodeValue.length; i++) {
const child = nodeValue[i - offset];
const res = visitNode(child, node, path, nodeKey, i - offset);
const res = visitNode(child, toTraverse, newPath, nodeKey, i - offset);
if (res?.removed) {
offset += 1;
}
}
} else {
visitNode(nodeValue, node, path, nodeKey);
visitNode(nodeValue, toTraverse, newPath, nodeKey);
}
});

Expand Down
33 changes: 33 additions & 0 deletions src/preprocessor/preprocessor.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,39 @@ true
`);
});

test('define inside if/else is properly expanded when the if branch is chosen', () => {
const program = `
#define MACRO
#ifdef MACRO
#define BRANCH a
#else
#define BRANCH b
#endif
BRANCH
`;
const ast = parse(program);
preprocessAst(ast);
expect(generate(ast)).toBe(`
a
`);
});

test('define inside if/else is properly expanded when the else branch is chosen', () => {
const program = `
#ifdef MACRO
#define BRANCH a
#else
#define BRANCH b
#endif
BRANCH
`;
const ast = parse(program);
preprocessAst(ast);
expect(generate(ast)).toBe(`
b
`);
});

test('ifdef inside else is properly expanded', () => {
// Regression: Make sure #ifdef MACRO inside #else isn't expanded
const program = `
Expand Down

0 comments on commit 9c1c4a9

Please sign in to comment.