Skip to content

Commit

Permalink
add: Support for structures and structure accessing
Browse files Browse the repository at this point in the history
  • Loading branch information
G0nzal0zz committed Jan 8, 2025
1 parent def5a3d commit 3631e01
Showing 1 changed file with 22 additions and 0 deletions.
22 changes: 22 additions & 0 deletions lib/Codegen/Codegen.hs
Original file line number Diff line number Diff line change
Expand Up @@ -171,6 +171,7 @@ instance ExprGen AT.Expr where
AT.UnaryOp {} -> generateUnaryOp expr
AT.Call {} -> generateFunctionCall expr
AT.ArrayAccess {} -> generateArrayAccess expr
AT.StructAccess {} -> generateStructAccess expr
AT.Cast {} -> generateCast expr
AT.For {} -> generateForLoop expr
AT.While {} -> generateWhileLoop expr
Expand All @@ -190,6 +191,12 @@ generateConstant lit = case lit of
AT.LArray elems -> do
constants <- mapM generateConstant elems
return $ C.Array (TD.typeOf $ head constants) constants
AT.LStruct fields -> do
-- We do not need the names of the fields
-- as we only use them when accessing the fields of the struct
let (_, values) = unzip fields
constants <- mapM generateConstant values
return $ C.Struct (Just (AST.Name (U.stringToByteString "asd"))) False constants

-- | Generate LLVM code for literals.
generateLiteral :: (MonadCodegen m) => AT.Expr -> m AST.Operand
Expand Down Expand Up @@ -410,6 +417,21 @@ generateArrayAccess (AT.ArrayAccess loc (AT.Var _ name _) indexExpr) = do
generateArrayAccess expr =
E.throwError $ CodegenError (U.getLoc expr) $ UnsupportedDefinition expr

-- | Generate LLVM code for struct access.
generateStructAccess :: (MonadCodegen m) => AT.Expr -> m AST.Operand
generateStructAccess (AT.StructAccess loc (AT.Var _ name (AT.TStruct _ fields)) field) = do
maybeVar <- getVar name
ptr <- case maybeVar of
Just structPtr -> return structPtr
Nothing -> E.throwError $ CodegenError loc $ VariableNotFound name
let fieldIndex = fromIntegral $ fromJust $ L.findIndex ((== field) . fst) fields
fieldPtr <- I.gep ptr [IC.int32 0, IC.int32 fieldIndex]
I.load fieldPtr 0
where
fromJust (Just x) = x
fromJust Nothing = error "fromJust: Nothing"
generateStructAccess expr = E.throwError $ CodegenError (U.getLoc expr) $ UnsupportedDefinition expr

-- | Generate LLVM code for type casts.
generateCast :: (MonadCodegen m) => AT.Expr -> m AST.Operand
generateCast (AT.Cast _ typ expr) = do
Expand Down

0 comments on commit 3631e01

Please # to comment.