WE CAN PASS ARGUMENTS TO FUNCTIONS!!!!!!

This commit is contained in:
SpookyDervish
2025-10-15 07:37:01 +11:00
parent 3c24b50a80
commit 39cc0429da
3 changed files with 38 additions and 13 deletions

View File

@@ -4,6 +4,7 @@ from AST import Node, NodeType, Program, Expression
from AST import ExpressionStatement, AssignmentStatement, BlockStatement, ReturnStatement, FunctionStatement, ReassignStatement, IfStatement
from AST import InfixExpression, CallExpression
from AST import IntegerLiteral, FloatLiteral, IdentifierLiteral, BooleanLiteral
from AST import FunctionParameter
from environment import Environment
@@ -116,8 +117,9 @@ class Compiler:
name: str = node.name.value
body: BlockStatement = node.body
params: list[IdentifierLiteral] = node.parameters
param_types: list[ir.Type] = [] # TODO
params: list[FunctionParameter] = node.parameters
param_names: list[str] = [p.name for p in params]
param_types: list[ir.Type] = [self.type_map[p.value_type] for p in params]
return_type: ir.Type = self.type_map[node.return_type]
@@ -130,9 +132,22 @@ class Compiler:
self.builder = ir.IRBuilder(block)
previous_env = self.environment
# storing the pointers to each parameter
params_ptr = []
for i, typ in enumerate(param_types):
ptr = self.builder.alloca(typ)
self.builder.store(func.args[i], ptr)
params_ptr.append(ptr)
# adding the params to the environment
previous_env = self.environment
self.environment = Environment(parent=self.environment)
for i, x in enumerate(zip(param_types, param_names)):
typ = param_types[i]
ptr = params_ptr[i]
self.environment.define(x[1], ptr, typ)
self.environment.define(name, func, return_type)
self.compile(body)
@@ -260,13 +275,17 @@ class Compiler:
return value, Type
def __visit_call_expression(self, node: CallExpression) -> None:
def __visit_call_expression(self, node: CallExpression) -> tuple[ir.Instruction, ir.Type]:
name: str = node.function.value
params: list[Expression] = node.arguments
args = []
types = []
# TODO
if len(params) > 0:
for x in params:
p_val, p_type = self.__resolve_value(x)
args.append(p_val)
types.append(p_type)
match name:
case _:

View File

@@ -4,16 +4,22 @@ target datalayout = ""
@"true" = constant i1 1
@"false" = constant i1 0
define i32 @"test"()
define i32 @"add"(i32 %".1", i32 %".2")
{
test_entry:
%".2" = add i32 77, 33
ret i32 %".2"
add_entry:
%".4" = alloca i32
store i32 %".1", i32* %".4"
%".6" = alloca i32
store i32 %".2", i32* %".6"
%".8" = load i32, i32* %".4"
%".9" = load i32, i32* %".6"
%".10" = add i32 %".8", %".9"
ret i32 %".10"
}
define i32 @"main"()
{
main_entry:
%".2" = call i32 @"test"()
%".2" = call i32 @"add"(i32 2, i32 3)
ret i32 %".2"
}

View File

@@ -10,9 +10,9 @@ import llvmlite.binding as llvm
from ctypes import CFUNCTYPE, c_int, c_float
LEXER_DEBUG: bool = False
PARSER_DEBUG: bool = True
COMPILER_DEBUG: bool = False
RUN_CODE: bool = False
PARSER_DEBUG: bool = False
COMPILER_DEBUG: bool = True
RUN_CODE: bool = True
if __name__ == "__main__":