Skip to content

Commit 30ab82f

Browse files
committed
Feature: Support function declare with number return type
1 parent 7e2a6e1 commit 30ab82f

3 files changed

Lines changed: 38 additions & 6 deletions

File tree

src/Backend/LLVM/index.ts

Lines changed: 29 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -27,16 +27,43 @@ export function passReturnStatement(parent: ReturnStatement, ctx: Context, build
2727
return builder.createRetVoid();
2828
}
2929

30+
if (parent.argument.type === 'Identifier') {
31+
return builder.createRet(
32+
buildFromIdentifier(parent.argument, ctx, builder)
33+
);
34+
}
35+
3036
throw new Error(
3137
`Unsupported ReturnStatement, only return without value is supported`
3238
);
3339
}
3440

3541
export function passFunctionDeclaration(parent: FunctionDeclaration, ctx: Context, builder: llvm.IRBuilder) {
3642
assert.ok(parent.id !== null, 'Function must be declared with name');
37-
assert.ok(parent.returnType, 'Function must be declared with return type');
3843

39-
let fnType = llvm.FunctionType.get(llvm.Type.getVoidTy(ctx.llvmContext), false);
44+
if (!parent.returnType) {
45+
throw Error('Function must be declared with return type');
46+
}
47+
48+
if (parent.returnType.type !== 'TSTypeAnnotation') {
49+
throw Error(
50+
`Function must be declared with TypeAnnotation return type, unexpected: "${parent.returnType.type}"`
51+
);
52+
}
53+
54+
let returnType = llvm.Type.getVoidTy(ctx.llvmContext);
55+
56+
switch (parent.returnType.typeAnnotation.type) {
57+
case 'TSNumberKeyword':
58+
returnType = llvm.Type.getInt32Ty(ctx.llvmContext);
59+
break;
60+
default:
61+
throw Error(
62+
`Function declared with unsupported return type, unexpected "${parent.returnType.typeAnnotation.type}"`
63+
);
64+
}
65+
66+
let fnType = llvm.FunctionType.get(returnType, false);
4067
let fn = llvm.Function.create(fnType, llvm.LinkageTypes.ExternalLinkage, (<Identifier>parent.id).name, ctx.llvmModule);
4168

4269
let block = llvm.BasicBlock.create(ctx.llvmContext, 'Entry', fn);

src/Frontend/TypeScript/index.ts

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,15 @@ import {parse} from '@babel/parser'
22

33
const example = `
44
{
5-
const a = 1;
6-
const b = 2;
7-
const c = a + b;
5+
function doMath(): number {
6+
const a = 1;
7+
const b = 2;
8+
const c = a + b;
9+
10+
return c;
11+
}
812
9-
puts(c);
13+
doMath();
1014
}
1115
`;
1216

src/cli.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,3 +18,4 @@ const llvmModule = generateModuleFromFile(ast);
1818
llvm.verifyModule(llvmModule);
1919

2020
console.log(llvmModule.print());
21+

0 commit comments

Comments
 (0)