Skip to content

Commit

Permalink
Merge pull request #206 from EpitechPromo2027/158-support-global-vari…
Browse files Browse the repository at this point in the history
…ables

158 support global variables
  • Loading branch information
Jabolol authored Jan 15, 2025
2 parents 662193a + 432260e commit c176f9d
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 0 deletions.
18 changes: 18 additions & 0 deletions examples/globals_variable.ff
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import "std/io.ff"

globalDouble: double = 0,2
globalInt: int = 76
globalChar: char = 'a'
globalBool: bool = true
structType :: struct {
hello -> int
}
globalStruct: structType = structType { hello = 123 }

main: never -> never = {
printf("double: %f\n" globalDouble)
printf("int: %d\n" globalInt)
printf("char: %c\n" globalChar)
printf("bool: %d\n" globalBool)
printf("struct: %d\n" globalStruct.hello)
}
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 c176f9d

Please # to comment.