From b337790c41b170b142e947d3012e346343a017a8 Mon Sep 17 00:00:00 2001 From: marabesi Date: Thu, 27 Jun 2024 11:32:59 +0200 Subject: [PATCH] fix: recursive ast for if statements --- vscode/src/cli/find-smells.ts | 2 +- vscode/src/modules/smells-detector.ts | 20 +++++++++++--------- 2 files changed, 12 insertions(+), 10 deletions(-) diff --git a/vscode/src/cli/find-smells.ts b/vscode/src/cli/find-smells.ts index 698b585..6d4393b 100644 --- a/vscode/src/cli/find-smells.ts +++ b/vscode/src/cli/find-smells.ts @@ -13,7 +13,7 @@ async function execute() { try { const fileContents = await fs.readFile(fileName, { encoding: 'utf8' }); const smellDetector = new SmellDetector(fileContents); - console.log(smellDetector.findAll()); + console.info(smellDetector.findAll()); } catch (err) { console.log(`[SMELLY] error: ${err}`); } diff --git a/vscode/src/modules/smells-detector.ts b/vscode/src/modules/smells-detector.ts index a7847fe..427214f 100644 --- a/vscode/src/modules/smells-detector.ts +++ b/vscode/src/modules/smells-detector.ts @@ -11,8 +11,9 @@ export class SmellDetector { findAll(): Smell[] { const smells: Smell[] = []; + const ifs: any[] = []; - const ifs = containsIfStatement(this.ast).filter((item: any) => item.type === Syntax.IfStatement); + findIfStatements(this.ast, ifs).filter((item: any) => item.type === Syntax.IfStatement); for (const statement of ifs) { smells.push({ @@ -30,16 +31,17 @@ export class SmellDetector { } } -function containsIfStatement(node: any) { - if (node.type === Syntax.IfStatement) { - return node; +function findIfStatements(node: any, ifStatements: any[] = []) { + if (node.type === 'IfStatement') { + ifStatements.push(node); } - for (const key in node) { + + // Recursively search in all child nodes + for (let key in node) { if (node[key] && typeof node[key] === 'object') { - if (containsIfStatement(node[key])) { - return node[key]; - } + findIfStatements(node[key], ifStatements); } } - return false; + + return ifStatements; } \ No newline at end of file