Skip to content

Commit

Permalink
Map ts.TypeAssertion and ts.AsExpression
Browse files Browse the repository at this point in the history
  • Loading branch information
knutwannheden committed Sep 26, 2024
1 parent b2fea46 commit 997e823
Show file tree
Hide file tree
Showing 8 changed files with 110 additions and 15 deletions.
2 changes: 1 addition & 1 deletion openrewrite/src/core/markers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,7 @@ export class ParseExceptionResult implements Marker {
this._exceptionType = exceptionType;
this._exceptionMessage = exceptionMessage;
this._message = message;
this._treeType = treeType;
this._treeType = treeType ?? null;
}

static build(parser: Parser, exception: Error): ParseExceptionResult {
Expand Down
37 changes: 32 additions & 5 deletions openrewrite/src/javascript/parser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ export class JavaScriptParser extends Parser {
}

sourcePathFromSourceText(prefix: string, sourceCode: string): string {
return prefix + "/source.js";
return prefix + "/source.ts";
}

static builder(): JavaScriptParser.Builder {
Expand Down Expand Up @@ -208,6 +208,14 @@ export class JavaScriptParserVisitor {
return this.mapLiteral(node, true);
}

visitNumberKeyword(node: ts.Node) {
return this.mapIdentifier(node, 'number');
}

visitStringKeyword(node: ts.Node) {
return this.mapIdentifier(node, 'string');
}

visitFalseKeyword(node: ts.FalseLiteral) {
return this.mapLiteral(node, false);
}
Expand Down Expand Up @@ -264,7 +272,7 @@ export class JavaScriptParserVisitor {
return this.mapIdentifier(node, node.text);
}

private mapIdentifier(node: ts.PrimaryExpression, name: string) {
private mapIdentifier(node: ts.Node, name: string) {
let type = this.mapType(node);
return new J.Identifier(
randomId(),
Expand Down Expand Up @@ -529,7 +537,18 @@ export class JavaScriptParserVisitor {
}

visitTypeAssertionExpression(node: ts.TypeAssertion) {
return this.visitUnknown(node);
return new J.TypeCast(
randomId(),
this.prefix(node),
Markers.EMPTY,
new J.ControlParentheses(
randomId(),
this.prefix(node.getFirstToken()!),
Markers.EMPTY,
this.rightPadded(this.convert(node.type), this.prefix(node.getChildAt(2)))
),
this.convert(node.expression)
);
}

visitParenthesizedExpression(node: ts.ParenthesizedExpression) {
Expand Down Expand Up @@ -606,7 +625,15 @@ export class JavaScriptParserVisitor {
}

visitAsExpression(node: ts.AsExpression) {
return this.visitUnknown(node);
return new JS.JsBinary(
randomId(),
this.prefix(node),
Markers.EMPTY,
this.convert(node.expression),
this.leftPadded(this.prefix(node.getChildAt(1)), JS.JsBinary.Type.As),
this.convert(node.type),
this.mapType(node)
);
}

visitNonNullExpression(node: ts.NonNullExpression) {
Expand Down Expand Up @@ -1128,7 +1155,7 @@ export class JavaScriptParserVisitor {
return this.prefix(getNextSibling(node)!);
}

private mapType(node: ts.Expression): JavaType | null {
private mapType(node: ts.Node): JavaType | null {
if (ts.isLiteralExpression(node)) {
if (ts.isNumericLiteral(node)) {
return JavaType.Primitive.of(JavaType.PrimitiveKind.Int);
Expand Down
7 changes: 4 additions & 3 deletions openrewrite/src/javascript/tree/tree.ts
Original file line number Diff line number Diff line change
Expand Up @@ -962,9 +962,10 @@ export class JsBinary extends JSMixin(Object) implements Expression, TypedTree {

export namespace JsBinary {
export enum Type {
IdentityEquals = 0,
IdentityNotEquals = 1,
In = 2,
As = 0,
IdentityEquals = 1,
IdentityNotEquals = 2,
In = 3,

}

Expand Down
13 changes: 13 additions & 0 deletions openrewrite/test/javascript/parser/as.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import {connect, disconnect, javaScript, rewriteRun} from '../testHarness';

describe('as mapping', () => {
beforeAll(() => connect());
afterAll(() => disconnect());

test('primitive type', () => {
rewriteRun(
//language=typescript
javaScript('1 as number')
);
});
});
13 changes: 13 additions & 0 deletions openrewrite/test/javascript/parser/cast.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import {connect, disconnect, javaScript, rewriteRun, typeScript} from '../testHarness';

describe('cast mapping', () => {
beforeAll(() => connect());
afterAll(() => disconnect());

test('primitive type', () => {
rewriteRun(
//language=typescript
typeScript('< string > "x"')
);
});
});
31 changes: 28 additions & 3 deletions openrewrite/test/javascript/testHarness.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,12 @@
import {Cursor, PrinterFactory, PrintOutputCapture, RecipeRunException, SourceFile} from '../../dist/core';
import {
Cursor,
InMemoryExecutionContext,
ParserInput,
PrinterFactory,
PrintOutputCapture,
RecipeRunException,
SourceFile
} from '../../dist/core';
import * as J from "../../dist/java/tree";
import * as JS from "../../dist/javascript/tree";
import dedent from "dedent";
Expand Down Expand Up @@ -68,9 +76,18 @@ export function rewriteRunWithOptions(options: RewriteTestOptions, ...sourceSpec

const parser = JavaScriptParser.builder().build();

export function javaScript(before: string, spec?: (sourceFile: JS.CompilationUnit) => void): SourceSpec {
function sourceFile(before: string, defaultPath: string, spec?: (sourceFile: JS.CompilationUnit) => void) {
return (options: RewriteTestOptions) => {
const [sourceFile] = parser.parseStrings(options.normalizeIndent ?? true ? dedent(before) : before) as Iterable<JS.CompilationUnit>;
const ctx = new InMemoryExecutionContext();
const [sourceFile] = parser.parseInputs(
[new ParserInput(
defaultPath,
null,
true,
() => Buffer.from(options.normalizeIndent ?? true ? dedent(before) : before)
)],
null,
ctx) as Iterable<JS.CompilationUnit>;
if (!(options.allowUnknowns ?? false)) {
try {
let unknowns: J.Unknown[] = [];
Expand All @@ -97,6 +114,14 @@ export function javaScript(before: string, spec?: (sourceFile: JS.CompilationUni
};
}

export function javaScript(before: string, spec?: (sourceFile: JS.CompilationUnit) => void): SourceSpec {
return sourceFile(before, 'test.js', spec);
}

export function typeScript(before: string, spec?: (sourceFile: JS.CompilationUnit) => void): SourceSpec {
return sourceFile(before, 'test.ts', spec);
}

function print(parsed: SourceFile) {
remoting.reset();
remoting.client?.reset();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -207,6 +207,9 @@ public J visitJsBinary(JS.JsBinary binary, PrintOutputCapture<P> p) {
visit(binary.getLeft(), p);
String keyword = "";
switch (binary.getOperator()) {
case As:
keyword = "as";
break;
case IdentityEquals:
keyword = "===";
break;
Expand Down Expand Up @@ -655,14 +658,26 @@ public J visitNewClass(J.NewClass newClass, PrintOutputCapture<P> p) {
return newClass;
}

@Override
public <T extends J> J visitControlParentheses(J.ControlParentheses<T> controlParens, PrintOutputCapture<P> p) {
beforeSyntax(controlParens, Space.Location.CONTROL_PARENTHESES_PREFIX, p);
if (getCursor().getParentTreeCursor().getValue() instanceof J.TypeCast) {
p.append('<');
visitRightPadded(controlParens.getPadding().getTree(), JRightPadded.Location.PARENTHESES, ">", p);
} else {
p.append('(');
visitRightPadded(controlParens.getPadding().getTree(), JRightPadded.Location.PARENTHESES, ")", p);
}
afterSyntax(controlParens, p);
return controlParens;
}

@Override
public J visitTypeCast(J.TypeCast typeCast, PrintOutputCapture<P> p) {
beforeSyntax(typeCast, Space.Location.TYPE_CAST_PREFIX, p);

visit(typeCast.getClazz(), p);
visit(typeCast.getExpression(), p);
visitSpace(typeCast.getClazz().getPrefix(), Space.Location.LANGUAGE_EXTENSION, p);
p.append("as");
visitRightPadded(typeCast.getClazz().getPadding().getTree(), JRightPadded.Location.NAMED_VARIABLE, p);

afterSyntax(typeCast, p);
return typeCast;
Expand Down
1 change: 1 addition & 0 deletions src/main/java/org/openrewrite/javascript/tree/JS.java
Original file line number Diff line number Diff line change
Expand Up @@ -884,6 +884,7 @@ public CoordinateBuilder.Expression getCoordinates() {
}

public enum Type {
As,
IdentityEquals,
IdentityNotEquals,
In
Expand Down

0 comments on commit 997e823

Please sign in to comment.