Skip to content

Commit

Permalink
Add some support for semicolon padding
Browse files Browse the repository at this point in the history
  • Loading branch information
knutwannheden committed Sep 24, 2024
1 parent 7bff7e9 commit 74ff6ef
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 10 deletions.
22 changes: 15 additions & 7 deletions openrewrite/src/javascript/parser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,7 @@ export class JavaScriptParserVisitor {
false,
null,
[],
this.rightPaddedList<J.Statement>(node.statements),
this.rightPaddedList(node.statements, this.semicolonPrefix),
Space.EMPTY
);
}
Expand All @@ -139,16 +139,22 @@ export class JavaScriptParserVisitor {
return [];
}

private rightPaddedList<T extends J.J>(nodes: ts.NodeArray<ts.Node>) {
return nodes.map((s) => {
return new JRightPadded(
this.visit(s) as T,
Space.EMPTY,
private rightPaddedList<N extends ts.Node, T extends J.J>(nodes: ts.NodeArray<N>, trailing?: (node: N) => Space) {
return nodes.map(n => {
return new JRightPadded<T>(
this.visit(n) as T,
trailing ? trailing(n) : Space.EMPTY,
Markers.EMPTY
);
});
}

private semicolonPrefix = (n: ts.Node) => {
const last = n.getLastToken();
return last?.kind == ts.SyntaxKind.SemicolonToken ? prefixFromNode(last, this.sourceFile) : Space.EMPTY;
}


visitClassDeclaration(node: ts.ClassDeclaration) {
// return new ClassDeclaration(randomId(), node.)
return this.visitUnknown(node);
Expand Down Expand Up @@ -515,7 +521,9 @@ export class JavaScriptParserVisitor {
null,
null,
[],
this.rightPaddedList(node.declarationList.declarations)
this.rightPaddedList(node.declarationList.declarations, n => {
return Space.EMPTY;
})
)
}

Expand Down
11 changes: 8 additions & 3 deletions openrewrite/test/javascript/parser.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import {JavaScriptParser} from "../../src/javascript";
import * as J from "../../src/java/tree";
import * as JS from "../../src/javascript/tree";
import dedent from "dedent";
import {JRightPadded} from "../../src/java/tree";

describe('Parser API', () => {
const parser = JavaScriptParser.builder().build();
Expand Down Expand Up @@ -43,15 +44,19 @@ describe('LST mapping', () => {
javaScript(
//language=javascript
`
const c = 1;
const c = 1 ;
/* c1*/ /*c2 */
const d = 1;
const d = 1 ;
`, cu => {
expect(cu).toBeDefined();
expect(cu.statements).toHaveLength(2);
cu.statements.forEach(statement => {
expect(statement).toBeInstanceOf(J.Unknown);
})
});
cu.padding.statements.forEach(statement => {
expect(statement.after.comments).toHaveLength(0);
expect(statement.after.whitespace).toBe(' ');
});
})
);
});
Expand Down

0 comments on commit 74ff6ef

Please sign in to comment.