Skip to content

Commit

Permalink
Basic support for if
Browse files Browse the repository at this point in the history
The `else` part is not yet covered.
  • Loading branch information
knutwannheden committed Sep 30, 2024
1 parent 413949a commit 7046854
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 2 deletions.
30 changes: 28 additions & 2 deletions openrewrite/src/javascript/parser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -215,7 +215,7 @@ export class JavaScriptParserVisitor {

private semicolonPaddedStatementList(statements: ts.NodeArray<ts.Statement>) {
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;
});
}
Expand Down Expand Up @@ -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) {
Expand Down Expand Up @@ -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 {
Expand Down
13 changes: 13 additions & 0 deletions openrewrite/test/javascript/parser/if.test.ts
Original file line number Diff line number Diff line change
@@ -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");')
);
});
});

0 comments on commit 7046854

Please sign in to comment.