{-
-- EPITECH PROJECT, 2026
-- Glados
-- File description:
-- Step2CallLabel
-}

module Compiler.ResolveLabels.Step2CallLabel (step2CallLabel) where

import Data.Text (Text)
import qualified Data.Map.Strict as Map
import qualified Data.Set as Set
import qualified Data.Text as T
import Compiler.Instruction (Instruction(..))
import Compiler.ResolveLabels.ResolveLabelsHelpers
    ( computeOffset
    , checkInt32Range
    , sizeOfCallInst
    )

step2CallLabel :: Map.Map Text Int -> Set.Set Int ->
    [Instruction] -> Int -> Text -> Either Text ([Instruction], Int)
step2CallLabel :: Map Text Int
-> Set Int
-> [Instruction]
-> Int
-> Text
-> Either Text ([Instruction], Int)
step2CallLabel Map Text Int
labelMap Set Int
starts [Instruction]
out Int
idx Text
name =
    case Text -> Map Text Int -> Maybe Int
forall k a. Ord k => k -> Map k a -> Maybe a
Map.lookup Text
name Map Text Int
labelMap of
        Maybe Int
Nothing -> Text -> Either Text ([Instruction], Int)
forall a b. a -> Either a b
Left (String -> Text
T.pack String
"Unknown label: " Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
name)
        Just Int
target -> 
            case Int -> Set Int -> Bool
forall a. Ord a => a -> Set a -> Bool
Set.member Int
target Set Int
starts of
                Bool
True  -> Int
-> [Instruction] -> Int -> Text -> Either Text ([Instruction], Int)
callLabelResult Int
target [Instruction]
out Int
idx Text
name
                Bool
False -> Text -> Either Text ([Instruction], Int)
forall a b. a -> Either a b
Left (String -> Text
T.pack
                    String
"Call target not at instruction boundary")

callLabelResult :: Int -> [Instruction] -> Int
    -> Text -> Either Text ([Instruction], Int)
callLabelResult :: Int
-> [Instruction] -> Int -> Text -> Either Text ([Instruction], Int)
callLabelResult Int
target [Instruction]
out Int
idx Text
name =
    let off64 :: Int64
off64 = Int -> Int -> Int64
computeOffset Int
target (Int
idx Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
sizeOfCallInst)
    in case Int64 -> Either Text Int32
checkInt32Range Int64
off64 of
        Left Text
err -> Text -> Either Text ([Instruction], Int)
forall a b. a -> Either a b
Left (String -> Text
T.pack String
"Call offset for label '" Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
name
            Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> String -> Text
T.pack String
"' " Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
err)
        Right Int32
off ->
            ([Instruction], Int) -> Either Text ([Instruction], Int)
forall a b. b -> Either a b
Right ([Instruction]
out [Instruction] -> [Instruction] -> [Instruction]
forall a. [a] -> [a] -> [a]
++ [Int -> Instruction
Call (Int32 -> Int
forall a b. (Integral a, Num b) => a -> b
fromIntegral Int32
off)], Int
idx Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
sizeOfCallInst)