fp-il

My bachelor project (unfinished)
Log | Files | Refs

ExpBuilder.py (1386B)


      1 from typing import Dict
      2 
      3 from antlr4 import TerminalNode
      4 from llvmlite import ir
      5 
      6 from gen import ANFVisitor
      7 from gen.ANFParser import ANFParser
      8 
      9 
     10 class ExpBuilder(ANFVisitor):
     11     module = ir.Module("Program")
     12     i_type = ir.IntType(64)
     13 
     14     def __init__(self):
     15         self.var_env: Dict[ir.Value] = dict()
     16         self.currentFunc: ir.Function | None = None
     17 
     18     def visitDef(self, ctx: ANFParser.DefContext):
     19         args = [i.getText() for i in ctx.IDENT()][1:]
     20         self.currentFunc = ir.Function(self.module,
     21                                     ir.FunctionType(self.i_type, [self.i_type] * len(args)),
     22                                     name=ctx.IDENT(0))
     23         self.visit(ctx.cexp())
     24 
     25 
     26     def visitTrue(self, ctx:ANFParser.TrueContext):
     27         return ir.Constant(self.i_type, True)
     28 
     29     def visitFalse(self, ctx: ANFParser.FalseContext):
     30         return ir.Constant(self.i_type, False)
     31 
     32     def visitVar(self, ctx:ANFParser.VarContext):
     33         var_name = ctx.IDENT().getText()
     34         return self.var_env[var_name]
     35 
     36     def visitNum(self, ctx:ANFParser.NumContext):
     37         number = int(ctx.NUMBER().getText())
     38 
     39 
     40     def visitLet(self, ctx:ANFParser.LetContext):
     41         var_name = ctx.IDENT().getText()
     42         self.var_env[var_name] = self.visit(ctx.funcall())
     43         self.currentFunc.append_basic_block(self.var_env[var_name])
     44         return self.visit(ctx.cexp())