Skip to content

Enable type casting #64

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 13 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
139 changes: 139 additions & 0 deletions src/ast/__tests__/expression-extractor.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1035,3 +1035,142 @@ describe("extract ClassInstanceCreationExpression correctly", () => {
expect(ast).toEqual(expectedAst);
});
});

describe("extract CastExpression correctly", () => {
it("extract CastExpression int to char correctly", () => {
const programStr = `
class Test {
void test() {
char c = (char) 65;
}
}
`;

const expectedAst: AST = {
kind: "CompilationUnit",
importDeclarations: [],
topLevelClassOrInterfaceDeclarations: [
{
kind: "NormalClassDeclaration",
classModifier: [],
typeIdentifier: "Test",
classBody: [
{
kind: "MethodDeclaration",
methodModifier: [],
methodHeader: {
result: "void",
identifier: "test",
formalParameterList: [],
},
methodBody: {
kind: "Block",
blockStatements: [
{
kind: "LocalVariableDeclarationStatement",
localVariableType: "char",
variableDeclaratorList: [
{
kind: "VariableDeclarator",
variableDeclaratorId: "c",
variableInitializer: {
kind: "CastExpression",
type: "char",
expression: {
kind: "Literal",
literalType: {
kind: "DecimalIntegerLiteral",
value: "65",
},
location: expect.anything(),
},
location: expect.anything(),
},
},
],
location: expect.anything(),
},
],
location: expect.anything(),
},
location: expect.anything(),
},
],
location: expect.anything(),
},
],
location: expect.anything(),
};

const ast = parse(programStr);
expect(ast).toEqual(expectedAst);
});

it("extract CastExpression double to int correctly", () => {
const programStr = `
class Test {
void test() {
int x = (int) 3.14;
}
}
`;

const expectedAst: AST = {
kind: "CompilationUnit",
importDeclarations: [],
topLevelClassOrInterfaceDeclarations: [
{
kind: "NormalClassDeclaration",
classModifier: [],
typeIdentifier: "Test",
classBody: [
{
kind: "MethodDeclaration",
methodModifier: [],
methodHeader: {
result: "void",
identifier: "test",
formalParameterList: [],
},
methodBody: {
kind: "Block",
blockStatements: [
{
kind: "LocalVariableDeclarationStatement",
localVariableType: "int",
variableDeclaratorList: [
{
kind: "VariableDeclarator",
variableDeclaratorId: "x",
variableInitializer: {
kind: "CastExpression",
type: "int",
expression: {
kind: "Literal",
literalType: {
kind: "DecimalFloatingPointLiteral",
value: "3.14",
}
},
location: expect.anything(),
},
},
],
location: expect.anything(),
},
],
location: expect.anything(),
},
location: expect.anything(),
},
],
location: expect.anything(),
},
],
location: expect.anything(),
};

const ast = parse(programStr);
expect(ast).toEqual(expectedAst);
});
});
61 changes: 61 additions & 0 deletions src/ast/astExtractor/expression-extractor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
ArgumentListCtx,
BaseJavaCstVisitorWithDefaults,
BinaryExpressionCtx,
CastExpressionCtx,
ClassOrInterfaceTypeToInstantiateCtx,
BooleanLiteralCtx,
ExpressionCstNode,
Expand Down Expand Up @@ -86,6 +87,62 @@
}
}

castExpression(ctx: CastExpressionCtx) {
// Handle primitive cast expressions
if (ctx.primitiveCastExpression && ctx.primitiveCastExpression?.length > 0) {
const primitiveCast = ctx.primitiveCastExpression[0];
const type = this.extractType(primitiveCast.children.primitiveType[0]);
const expression = this.visit(primitiveCast.children.unaryExpression[0]);
return {
kind: "CastExpression",
type: type,
expression: expression,
location: this.location,
};
}

throw new Error("Invalid CastExpression format.");
}

private extractType(typeCtx: any): string {
// Check for the 'primitiveType' node
if (typeCtx.name === "primitiveType" && typeCtx.children) {
const { children } = typeCtx;

// Handle 'numericType' (e.g., int, char, float, double)
if (children.numericType) {
const numericTypeCtx = children.numericType[0];

if (numericTypeCtx.children.integralType) {
// Handle integral types (e.g., char, int)
const integralTypeCtx = numericTypeCtx.children.integralType[0];

// Extract the specific type (e.g., 'char', 'int')
for (const key in integralTypeCtx.children) {
if (integralTypeCtx.children[key][0].image) {
return integralTypeCtx.children[key][0].image;
}
}
}

if (numericTypeCtx.children.floatingPointType) {
// Handle floating-point types (e.g., float, double)
const floatingPointTypeCtx = numericTypeCtx.children.floatingPointType[0];

Check warning on line 130 in src/ast/astExtractor/expression-extractor.ts

View workflow job for this annotation

GitHub Actions / Coverage annotations (🧪 jest-coverage-report-action)

🧾 Statement is not covered

Warning! Not covered statement

// Extract the specific type (e.g., 'float', 'double')
for (const key in floatingPointTypeCtx.children) {
if (floatingPointTypeCtx.children[key][0].image) {
return floatingPointTypeCtx.children[key][0].image;

Check warning on line 135 in src/ast/astExtractor/expression-extractor.ts

View workflow job for this annotation

GitHub Actions / Coverage annotations (🧪 jest-coverage-report-action)

🧾 Statement is not covered

Warning! Not covered statement
}

Check warning on line 136 in src/ast/astExtractor/expression-extractor.ts

View workflow job for this annotation

GitHub Actions / Coverage annotations (🧪 jest-coverage-report-action)

🧾 Statement is not covered

Warning! Not covered statement

Check warning on line 136 in src/ast/astExtractor/expression-extractor.ts

View workflow job for this annotation

GitHub Actions / Coverage annotations (🧪 jest-coverage-report-action)

🌿 Branch is not covered

Warning! Not covered branch
}

Check warning on line 137 in src/ast/astExtractor/expression-extractor.ts

View workflow job for this annotation

GitHub Actions / Coverage annotations (🧪 jest-coverage-report-action)

🧾 Statement is not covered

Warning! Not covered statement
}

Check warning on line 138 in src/ast/astExtractor/expression-extractor.ts

View workflow job for this annotation

GitHub Actions / Coverage annotations (🧪 jest-coverage-report-action)

🧾 Statement is not covered

Warning! Not covered statement

Check warning on line 138 in src/ast/astExtractor/expression-extractor.ts

View workflow job for this annotation

GitHub Actions / Coverage annotations (🧪 jest-coverage-report-action)

🌿 Branch is not covered

Warning! Not covered branch
}
}

throw new Error("Invalid type context in cast expression.");
}


private makeBinaryExpression(
operators: IToken[],
operands: UnaryExpressionCstNode[]
Expand Down Expand Up @@ -174,6 +231,10 @@
}

unaryExpression(ctx: UnaryExpressionCtx) {
if (ctx.primary[0].children.primaryPrefix[0].children.castExpression) {
return this.visit(ctx.primary[0].children.primaryPrefix[0].children.castExpression);
}

const node = this.visit(ctx.primary);
if (ctx.UnaryPrefixOperator) {
return {
Expand Down
8 changes: 7 additions & 1 deletion src/ast/types/blocks-and-statements.ts
Original file line number Diff line number Diff line change
Expand Up @@ -259,7 +259,7 @@ export interface Assignment extends BaseNode {
}

export type LeftHandSide = ExpressionName | ArrayAccess;
export type UnaryExpression = PrefixExpression | PostfixExpression;
export type UnaryExpression = PrefixExpression | PostfixExpression | CastExpression;

export interface PrefixExpression extends BaseNode {
kind: "PrefixExpression";
Expand Down Expand Up @@ -289,3 +289,9 @@ export interface TernaryExpression extends BaseNode {
consequent: Expression;
alternate: Expression;
}

export interface CastExpression extends BaseNode {
kind: "CastExpression";
type: UnannType;
expression: Expression;
}
1 change: 1 addition & 0 deletions src/compiler/__tests__/__utils__/test-utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ const binaryWriter = new BinaryWriter();

export function runTest(program: string, expectedLines: string[]) {
const ast = parser.parse(program);
console.log(JSON.stringify(ast, null, 2) + "\n");
expect(ast).not.toBeNull();

if (debug) {
Expand Down
4 changes: 4 additions & 0 deletions src/compiler/__tests__/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,11 @@ import { methodInvocationTest } from "./tests/methodInvocation.test";
import { importTest } from "./tests/import.test";
import { arrayTest } from "./tests/array.test";
import { classTest } from "./tests/class.test";
import { assignmentExpressionTest } from './tests/assignmentExpression.test'
import { castExpressionTest } from './tests/castExpression.test'

describe("compiler tests", () => {
castExpressionTest();
printlnTest();
variableDeclarationTest();
arithmeticExpressionTest();
Expand All @@ -22,4 +25,5 @@ describe("compiler tests", () => {
importTest();
arrayTest();
classTest();
assignmentExpressionTest();
})
52 changes: 52 additions & 0 deletions src/compiler/__tests__/tests/arithmeticExpression.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,58 @@ const testCases: testCase[] = [
expectedLines: ["-2147483648", "-32769", "-32768",
"-129", "-128", "-1", "0", "1", "127", "128", "32767", "32768", "2147483647"],
},
{
comment: "Mixed int and float addition (order swapped)",
program: `
public class Main {
public static void main(String[] args) {
int a = 5;
float b = 2.5f;
System.out.println(a + b);
}
}
`,
expectedLines: ["7.5"],
},
{
comment: "Mixed long and double multiplication",
program: `
public class Main {
public static void main(String[] args) {
double a = 3.5;
long b = 10L;
System.out.println(a * b);
}
}
`,
expectedLines: ["35.0"],
},
{
comment: "Mixed long and double multiplication (order swapped)",
program: `
public class Main {
public static void main(String[] args) {
long a = 10L;
double b = 3.5;
System.out.println(a * b);
}
}
`,
expectedLines: ["35.0"],
},
{
comment: "Mixed int and double division",
program: `
public class Main {
public static void main(String[] args) {
double a = 2.0;
int b = 5;
System.out.println(a / b);
}
}
`,
expectedLines: ["0.4"],
}
];

export const arithmeticExpressionTest = () => describe("arithmetic expression", () => {
Expand Down
Loading
Loading