handle unit return

This commit is contained in:
Edgar 2024-02-04 15:57:26 +01:00
parent 497072760d
commit db6b6e980b
No known key found for this signature in database
GPG key ID: 70ADAE8F35904387
4 changed files with 29 additions and 9 deletions

View file

@ -136,19 +136,26 @@ fn compile_module(ctx: &ModuleCompileCtx, module: &ir::ModuleBody) {
}
fn compile_fn_signature(ctx: &ModuleCompileCtx, body: &ir::Body) {
let (args, ret_type) = { (body.get_args(), body.ret_type.clone().unwrap()) };
let name = ctx.ctx.symbols.get(&body.def_id).unwrap();
info!("compiling fn sig: {}", name);
let (args, ret_type) = { (body.get_args(), body.ret_type.clone()) };
let args: Vec<BasicMetadataTypeEnum> = args
.iter()
.map(|x| compile_basic_type(ctx, &x.ty).into())
.collect();
let ret_type = compile_basic_type(ctx, &ret_type);
let name = ctx.ctx.symbols.get(&body.def_id).unwrap();
info!("compiling fn sig: {}", name);
// let ret_type = compile_basic_type(ctx, &ret_type);
let fn_type = if let ir::TypeKind::Unit = ret_type.kind {
ctx.ctx.context.void_type().fn_type(&args, false)
} else {
compile_basic_type(ctx, &ret_type).fn_type(&args, false)
};
ctx.module.add_function(
name,
ret_type.fn_type(&args, false),
fn_type,
Some(if body.is_extern {
inkwell::module::Linkage::AvailableExternally
} else if body.is_pub {
@ -381,7 +388,7 @@ fn compile_type<'a>(
.functions
.get(def_id)
.unwrap();
(fn_body.get_args(), fn_body.ret_type.clone().unwrap())
(fn_body.get_args(), fn_body.ret_type.clone())
};
let args: Vec<BasicMetadataTypeEnum> = args

View file

@ -36,7 +36,7 @@ pub struct Body {
pub def_id: DefId,
pub is_pub: bool,
pub is_extern: bool,
pub ret_type: Option<TypeInfo>,
pub ret_type: TypeInfo,
pub locals: SmallVec<[Local; 4]>,
pub blocks: SmallVec<[BasicBlock; 8]>,
pub fn_span: Span,

View file

@ -122,7 +122,14 @@ fn lower_function(
let body = ir::Body {
def_id,
ret_type: func.return_type.as_ref().map(|x| lower_type(&mut ctx, x)),
ret_type: func
.return_type
.as_ref()
.map(|x| lower_type(&mut ctx, x))
.unwrap_or_else(|| TypeInfo {
span: None,
kind: ir::TypeKind::Unit,
}),
locals: Default::default(),
blocks: Default::default(),
fn_span: func.span,
@ -543,7 +550,7 @@ fn lower_value(
fn lower_return(builder: &mut BodyBuilder, info: &ast::ReturnStmt) {
let ret_type = builder.body.ret_type.clone();
if let Some(value) = &info.value {
let rvalue = lower_expr(builder, value, ret_type.as_ref());
let rvalue = lower_expr(builder, value, Some(&ret_type));
let ret_local = builder.ret_local.unwrap();
builder.statements.push(Statement {

View file

@ -5,4 +5,10 @@ mod Main {
x = 4;
return x;
}
pub fn a() {
let mut x: i32 = 2;
x = 4;
return;
}
}