From 7046854f6300ab1510741aed793c950217f7194b Mon Sep 17 00:00:00 2001 From: Knut Wannheden Date: Mon, 30 Sep 2024 12:16:19 +0200 Subject: [PATCH] Basic support for `if` The `else` part is not yet covered. --- openrewrite/src/javascript/parser.ts | 30 +++++++++++++++++-- openrewrite/test/javascript/parser/if.test.ts | 13 ++++++++ 2 files changed, 41 insertions(+), 2 deletions(-) create mode 100644 openrewrite/test/javascript/parser/if.test.ts diff --git a/openrewrite/src/javascript/parser.ts b/openrewrite/src/javascript/parser.ts index 4c86960a..ba9f3a86 100644 --- a/openrewrite/src/javascript/parser.ts +++ b/openrewrite/src/javascript/parser.ts @@ -215,7 +215,7 @@ export class JavaScriptParserVisitor { private semicolonPaddedStatementList(statements: ts.NodeArray) { return this.rightPaddedList([...statements], this.semicolonPrefix, n => { - const last = n.getLastToken(); + const last = n.getChildAt(n.getChildCount(this.sourceFile) - 1, this.sourceFile); return last?.kind == ts.SyntaxKind.SemicolonToken ? Markers.build([new Semicolon(randomId())]) : Markers.EMPTY; }); } @@ -1193,7 +1193,24 @@ export class JavaScriptParserVisitor { } visitIfStatement(node: ts.IfStatement) { - return this.visitUnknown(node); + const semicolonAfterThen = node.thenStatement.getLastToken()?.kind == ts.SyntaxKind.SemicolonToken; + return new J.If( + randomId(), + this.prefix(node), + Markers.EMPTY, + new J.ControlParentheses( + randomId(), + this.prefix(this.findChildNode(node, ts.SyntaxKind.OpenParenToken)!), + Markers.EMPTY, + this.rightPadded(this.visit(node.expression), this.suffix(node.expression)) + ), + this.rightPadded( + this.convert(node.thenStatement), + semicolonAfterThen ? this.prefix(node.thenStatement.getLastToken()!) : Space.EMPTY, + semicolonAfterThen ? Markers.build([new Semicolon(randomId())]) : Markers.EMPTY + ), + node.elseStatement ? this.visit(node.elseStatement) : null + ); } visitDoStatement(node: ts.DoStatement) { @@ -1828,6 +1845,15 @@ export class JavaScriptParserVisitor { this.prefix(nodes[nodes.length - 1]) ); } + + private findChildNode(node: ts.Node, kind: ts.SyntaxKind): ts.Node | undefined { + for (let i = 0; i < node.getChildCount(); i++) { + if (node.getChildAt(i).kind == kind) { + return node.getChildAt(i); + } + } + return undefined; + } } function prefixFromNode(node: ts.Node, sourceFile: ts.SourceFile): Space { diff --git a/openrewrite/test/javascript/parser/if.test.ts b/openrewrite/test/javascript/parser/if.test.ts new file mode 100644 index 00000000..1444d2a6 --- /dev/null +++ b/openrewrite/test/javascript/parser/if.test.ts @@ -0,0 +1,13 @@ +import {connect, disconnect, rewriteRun, typeScript} from '../testHarness'; + +describe('if mapping', () => { + beforeAll(() => connect()); + afterAll(() => disconnect()); + + test('simple', () => { + rewriteRun( + //language=typescript + typeScript('if (true) console.log("foo");') + ); + }); +});