Skip to content

Commit

Permalink
add: globall variables
Browse files Browse the repository at this point in the history
  • Loading branch information
G0nzal0zz committed Jan 15, 2025
1 parent 662193a commit bdda3e3
Showing 1 changed file with 17 additions and 0 deletions.
17 changes: 17 additions & 0 deletions lib/Codegen/Codegen.hs
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,7 @@ data CodegenErrorType
| ContinueOutsideLoop
| BreakOutsideLoop
| UnsupportedConversion T.Type T.Type
| UnsupportedGlobalDeclaration AT.Expr
deriving (Show)

instance Show CodegenError where
Expand Down Expand Up @@ -127,6 +128,7 @@ showErrorType err = case err of
ContinueOutsideLoop -> "Continue statement outside loop"
BreakOutsideLoop -> "Break statement outside loop"
UnsupportedConversion from to -> "Unsupported conversion from " ++ show from ++ " to " ++ show to
UnsupportedGlobalDeclaration expr -> "Unsupported global declaration: " ++ show expr

-- | Variable binding typeclass.
class (Monad m) => VarBinding m where
Expand Down Expand Up @@ -181,8 +183,23 @@ generateGlobal :: (MonadCodegen m) => AT.Expr -> m ()
generateGlobal expr = case expr of
AT.Function {} -> CM.void $ generateFunction expr
AT.ForeignFunction {} -> CM.void $ generateForeignFunction expr
AT.Declaration {} -> CM.void $ generateGlobalDeclaration expr
_ -> E.throwError $ CodegenError (SU.getLoc expr) $ UnsupportedTopLevel expr

generateGlobalDeclaration :: (MonadCodegen m) => AT.Expr -> m ()
generateGlobalDeclaration (AT.Declaration _ name typ initExpr) = do
let varType = toLLVM typ
case initExpr of
Just (AT.Lit loc lit) -> do
initConstant <- generateConstant lit loc
var <- M.global (AST.Name $ U.stringToByteString name) varType initConstant
addGlobalVar name var
Nothing -> do
var <- M.global (AST.Name $ U.stringToByteString name) varType (C.Undef varType)
addGlobalVar name var
Just expr -> E.throwError $ CodegenError (SU.getLoc expr) $ UnsupportedGlobalDeclaration expr
generateGlobalDeclaration expr = E.throwError $ CodegenError (SU.getLoc expr) $ UnsupportedGlobalDeclaration expr

-- Generates a fresh unique name.
fresh :: (MonadCodegen m) => m AST.Name
fresh = do
Expand Down

0 comments on commit bdda3e3

Please # to comment.