{- |
Module      : LH.Text.Parser.Monad
Description : The parser monad.
Copyright   : (c) Hangil Kim, 2026
                  Kairon Johnson, 2026
                  Leonidas Sallos, 2026
                  Oscar Abelanet, 2026
License     : MIT
Maintainer  : kimhang@oregonstate.edu
Stability   : experimental

This module provides the parser monad for Layered Haskell.
Consequently, it includes definitions for a custom Alex wrapper and a representation of errors and state.
-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE OverloadedStrings #-}
module LH.Text.Parser.Monad (
    -- * A wrapper for Alex
    AlexInput (..), alexGetByte, alexInputPrevChar,
    -- * The parser monad
    LHsParser (..), runLHsParser,
    -- ** State
    LHsState (..), getInput, setInput,
    -- ** Startcodes
    LHsStcd (..), getStcd, pushStcd, popStcd,
    -- ** Layout
    getInnermostLayout, pushLayout, popLayout,
    -- ** Errors
    LHsTextError (..)
    ) where

import Control.Monad.Except       (MonadError)
import Control.Monad.State.Strict 
    (MonadState, gets, modify,
     StateT, evalStateT)

import Data.Char  (ord)
import Data.Maybe (listToMaybe)
import Data.Text  (Text)
import Data.Word  (Word8)

import Errata

import qualified Data.ByteString    as Byte
import qualified Data.Text          as Text
import qualified Data.Text.Encoding as Text

import LH.Data.Error  (LHsError (buildError), underline, (+>))
import LH.Data.SrcLoc (LHsPos (..), LHsSpan (..))
import LH.Text.Token  (LHsToken (..))

-------------------------------------------------------------------------------
-- Definitions for an Alex wrapper
-- (i.e., a set of definitions that customize how the lexer Alex generates will 
--  interact with input and output.)

-- | A representation of the current state of the input stream being tokenized.
data AlexInput = AlexInput
    { AlexInput -> LHsPos
aiPos   :: !LHsPos    -- ^ The current position in the source.
    , AlexInput -> Char
aiPrev  :: !Char      -- ^ The previous character read.
    , AlexInput -> [Word8]
aiBytes :: [Word8]    -- ^ The remaining input represented as a sequence of bytes.
    , AlexInput -> Text
aiText  :: !Text      -- ^ The remaining input represented as 'Text'.
    }

-- | Reads the next character from the input and advances the input state.
nextChar :: AlexInput -> Maybe (Char, AlexInput)
nextChar :: AlexInput -> Maybe (Char, AlexInput)
nextChar (AlexInput LHsPos
pos Char
_ [Word8]
_ Text
txt) = do
    (Char
c, Text
txt') <- Text -> Maybe (Char, Text)
Text.uncons Text
txt
    (Char, AlexInput) -> Maybe (Char, AlexInput)
forall a. a -> Maybe a
Just (Char
c, LHsPos -> Char -> [Word8] -> Text -> AlexInput
AlexInput (Char -> LHsPos -> LHsPos
advance Char
c LHsPos
pos) Char
c [] Text
txt')
    where
        -- | Advances the source position after consuming a character.
        advance :: Char -> LHsPos -> LHsPos
        advance :: Char -> LHsPos -> LHsPos
advance Char
'\n' (LHsPos Int
l Int
_) = Int -> Int -> LHsPos
LHsPos (Int
1 Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
l) Int
1
        advance Char
_    (LHsPos Int
l Int
c) = Int -> Int -> LHsPos
LHsPos Int
l (Int
1 Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
c)

-- | Encodes a character into its UTF-8 byte representation.
utf8 :: Char -> [Word8]
utf8 :: Char -> [Word8]
utf8 Char
c
    -- ASCII characters are converted directly into a single byte.
    | Char
c Char -> Char -> Bool
forall a. Ord a => a -> a -> Bool
< Char
'\x80' = [Int -> Word8
forall a b. (Integral a, Num b) => a -> b
fromIntegral (Char -> Int
ord Char
c)]
    -- All other characters are encoded using a UTF-8 encoder.
    | Bool
otherwise  = ByteString -> [Word8]
Byte.unpack (Text -> ByteString
Text.encodeUtf8 (Char -> Text
Text.singleton Char
c))

-- | Fetches the next byte from the input and returns an updated input.
alexGetByte :: AlexInput -> Maybe (Word8, AlexInput)
alexGetByte :: AlexInput -> Maybe (Word8, AlexInput)
alexGetByte inp :: AlexInput
inp@AlexInput { aiBytes :: AlexInput -> [Word8]
aiBytes = Word8
b:[Word8]
bs } = (Word8, AlexInput) -> Maybe (Word8, AlexInput)
forall a. a -> Maybe a
Just (Word8
b, AlexInput
inp { aiBytes = bs })
alexGetByte AlexInput
inp = do
    (Char
c, AlexInput
inp') <- AlexInput -> Maybe (Char, AlexInput)
nextChar AlexInput
inp
    Word8
b:[Word8]
bs      <- [Word8] -> Maybe [Word8]
forall a. a -> Maybe a
forall (m :: * -> *) a. Monad m => a -> m a
return (Char -> [Word8]
utf8 Char
c)
    (Word8, AlexInput) -> Maybe (Word8, AlexInput)
forall a. a -> Maybe a
forall (m :: * -> *) a. Monad m => a -> m a
return (Word8
b, AlexInput
inp' { aiBytes = bs })

-- | Returns the character previously read from the input.
alexInputPrevChar :: AlexInput -> Char
alexInputPrevChar :: AlexInput -> Char
alexInputPrevChar = AlexInput -> Char
aiPrev

-------------------------------------------------------------------------------
-- Definitions for a parser monad with basic error handling 

-- | A parser monad with state ('LHsState') and errors ('LHsTextError').
newtype LHsParser a = LHsParser (StateT LHsState (Either LHsTextError) a)
    deriving ((forall a b. (a -> b) -> LHsParser a -> LHsParser b)
-> (forall a b. a -> LHsParser b -> LHsParser a)
-> Functor LHsParser
forall a b. a -> LHsParser b -> LHsParser a
forall a b. (a -> b) -> LHsParser a -> LHsParser b
forall (f :: * -> *).
(forall a b. (a -> b) -> f a -> f b)
-> (forall a b. a -> f b -> f a) -> Functor f
$cfmap :: forall a b. (a -> b) -> LHsParser a -> LHsParser b
fmap :: forall a b. (a -> b) -> LHsParser a -> LHsParser b
$c<$ :: forall a b. a -> LHsParser b -> LHsParser a
<$ :: forall a b. a -> LHsParser b -> LHsParser a
Functor, Functor LHsParser
Functor LHsParser =>
(forall a. a -> LHsParser a)
-> (forall a b. LHsParser (a -> b) -> LHsParser a -> LHsParser b)
-> (forall a b c.
    (a -> b -> c) -> LHsParser a -> LHsParser b -> LHsParser c)
-> (forall a b. LHsParser a -> LHsParser b -> LHsParser b)
-> (forall a b. LHsParser a -> LHsParser b -> LHsParser a)
-> Applicative LHsParser
forall a. a -> LHsParser a
forall a b. LHsParser a -> LHsParser b -> LHsParser a
forall a b. LHsParser a -> LHsParser b -> LHsParser b
forall a b. LHsParser (a -> b) -> LHsParser a -> LHsParser b
forall a b c.
(a -> b -> c) -> LHsParser a -> LHsParser b -> LHsParser c
forall (f :: * -> *).
Functor f =>
(forall a. a -> f a)
-> (forall a b. f (a -> b) -> f a -> f b)
-> (forall a b c. (a -> b -> c) -> f a -> f b -> f c)
-> (forall a b. f a -> f b -> f b)
-> (forall a b. f a -> f b -> f a)
-> Applicative f
$cpure :: forall a. a -> LHsParser a
pure :: forall a. a -> LHsParser a
$c<*> :: forall a b. LHsParser (a -> b) -> LHsParser a -> LHsParser b
<*> :: forall a b. LHsParser (a -> b) -> LHsParser a -> LHsParser b
$cliftA2 :: forall a b c.
(a -> b -> c) -> LHsParser a -> LHsParser b -> LHsParser c
liftA2 :: forall a b c.
(a -> b -> c) -> LHsParser a -> LHsParser b -> LHsParser c
$c*> :: forall a b. LHsParser a -> LHsParser b -> LHsParser b
*> :: forall a b. LHsParser a -> LHsParser b -> LHsParser b
$c<* :: forall a b. LHsParser a -> LHsParser b -> LHsParser a
<* :: forall a b. LHsParser a -> LHsParser b -> LHsParser a
Applicative, Applicative LHsParser
Applicative LHsParser =>
(forall a b. LHsParser a -> (a -> LHsParser b) -> LHsParser b)
-> (forall a b. LHsParser a -> LHsParser b -> LHsParser b)
-> (forall a. a -> LHsParser a)
-> Monad LHsParser
forall a. a -> LHsParser a
forall a b. LHsParser a -> LHsParser b -> LHsParser b
forall a b. LHsParser a -> (a -> LHsParser b) -> LHsParser b
forall (m :: * -> *).
Applicative m =>
(forall a b. m a -> (a -> m b) -> m b)
-> (forall a b. m a -> m b -> m b)
-> (forall a. a -> m a)
-> Monad m
$c>>= :: forall a b. LHsParser a -> (a -> LHsParser b) -> LHsParser b
>>= :: forall a b. LHsParser a -> (a -> LHsParser b) -> LHsParser b
$c>> :: forall a b. LHsParser a -> LHsParser b -> LHsParser b
>> :: forall a b. LHsParser a -> LHsParser b -> LHsParser b
$creturn :: forall a. a -> LHsParser a
return :: forall a. a -> LHsParser a
Monad, MonadState LHsState, MonadError LHsTextError)

-- | Runs a 'LHsParser' against an input 'Text'.
runLHsParser :: LHsParser a -> Text -> Either LHsTextError a
runLHsParser :: forall a. LHsParser a -> Text -> Either LHsTextError a
runLHsParser (LHsParser StateT LHsState (Either LHsTextError) a
m) Text
src = 
    StateT LHsState (Either LHsTextError) a
-> LHsState -> Either LHsTextError a
forall (m :: * -> *) s a. Monad m => StateT s m a -> s -> m a
evalStateT StateT LHsState (Either LHsTextError) a
m (AlexInput -> [LHsStcd] -> [Int] -> LHsState
LHsState (LHsPos -> Char -> [Word8] -> Text -> AlexInput
AlexInput LHsPos
initPos Char
initPrev [Word8]
forall a. [a]
initBytes Text
src) [LHsStcd]
forall a. [a]
initStack [Int]
forall a. [a]
initStack)
    where
        initPos :: LHsPos
initPos   = Int -> Int -> LHsPos
LHsPos Int
1 Int
1
        initPrev :: Char
initPrev  = Char
'\n'
        initBytes :: [a]
initBytes = []
        initStack :: [a]
initStack = []

-------------------------------------------------------------------------------
-- Parser state

-- | The parser state, which keeps track of the current input and two stacks.
data LHsState = LHsState
    { LHsState -> AlexInput
stInput  :: !AlexInput    -- ^ The current input.
    , LHsState -> [LHsStcd]
stStcds  :: [LHsStcd]     -- ^ A stack of startcodes. When empty, the lexer is in the default startcode @0@.
    , LHsState -> [Int]
stLayout :: [Int]         -- ^ A stack of the columns of open layout blocks.
    }

-- | Retrieves the current input. 
getInput :: LHsParser AlexInput
getInput :: LHsParser AlexInput
getInput = (LHsState -> AlexInput) -> LHsParser AlexInput
forall s (m :: * -> *) a. MonadState s m => (s -> a) -> m a
gets LHsState -> AlexInput
stInput

-- | Sets the current input. 
setInput :: AlexInput -> LHsParser ()
setInput :: AlexInput -> LHsParser ()
setInput AlexInput
inp = (LHsState -> LHsState) -> LHsParser ()
forall s (m :: * -> *). MonadState s m => (s -> s) -> m ()
modify (\LHsState
st -> LHsState
st { stInput = inp })

-------------------------------------------------------------------------------
-- Startcodes

-- | A startcode paired with the position at which it was pushed onto the stack.
data LHsStcd = LHsStcd !Int !LHsPos

-- | Retrieves the current startcode. 
getStcd :: LHsParser Int
getStcd :: LHsParser Int
getStcd = (LHsState -> Int) -> LHsParser Int
forall s (m :: * -> *) a. MonadState s m => (s -> a) -> m a
gets (Int -> (LHsStcd -> Int) -> Maybe LHsStcd -> Int
forall b a. b -> (a -> b) -> Maybe a -> b
maybe Int
0 (\(LHsStcd Int
code LHsPos
_) -> Int
code) (Maybe LHsStcd -> Int)
-> (LHsState -> Maybe LHsStcd) -> LHsState -> Int
forall b c a. (b -> c) -> (a -> b) -> a -> c
. [LHsStcd] -> Maybe LHsStcd
forall a. [a] -> Maybe a
listToMaybe ([LHsStcd] -> Maybe LHsStcd)
-> (LHsState -> [LHsStcd]) -> LHsState -> Maybe LHsStcd
forall b c a. (b -> c) -> (a -> b) -> a -> c
. LHsState -> [LHsStcd]
stStcds)

-- | Pushes a startcode onto the stack.
pushStcd :: Int -> LHsPos -> LHsParser ()
pushStcd :: Int -> LHsPos -> LHsParser ()
pushStcd Int
code LHsPos
pos = (LHsState -> LHsState) -> LHsParser ()
forall s (m :: * -> *). MonadState s m => (s -> s) -> m ()
modify (\LHsState
st -> LHsState
st { stStcds = LHsStcd code pos : stStcds st })

-- | Pops the current startcode from the stack.
popStcd :: LHsParser ()
popStcd :: LHsParser ()
popStcd = (LHsState -> LHsState) -> LHsParser ()
forall s (m :: * -> *). MonadState s m => (s -> s) -> m ()
modify (\LHsState
st -> LHsState
st { stStcds = drop 1 (stStcds st) })

-------------------------------------------------------------------------------
-- Layout

-- | Retrieves the column of the innermost open layout block, if present.
getInnermostLayout :: LHsParser (Maybe Int)
getInnermostLayout :: LHsParser (Maybe Int)
getInnermostLayout = (LHsState -> Maybe Int) -> LHsParser (Maybe Int)
forall s (m :: * -> *) a. MonadState s m => (s -> a) -> m a
gets ([Int] -> Maybe Int
forall a. [a] -> Maybe a
listToMaybe ([Int] -> Maybe Int)
-> (LHsState -> [Int]) -> LHsState -> Maybe Int
forall b c a. (b -> c) -> (a -> b) -> a -> c
. LHsState -> [Int]
stLayout)

-- | Pushes a column of an open layout block onto the stack.
pushLayout :: Int -> LHsParser ()
pushLayout :: Int -> LHsParser ()
pushLayout Int
c = (LHsState -> LHsState) -> LHsParser ()
forall s (m :: * -> *). MonadState s m => (s -> s) -> m ()
modify (\LHsState
st -> LHsState
st { stLayout = c : stLayout st })

-- | Pops a column of an open layout block from the stack.
popLayout :: LHsParser ()
popLayout :: LHsParser ()
popLayout = (LHsState -> LHsState) -> LHsParser ()
forall s (m :: * -> *). MonadState s m => (s -> s) -> m ()
modify (\LHsState
st -> LHsState
st { stLayout = drop 1 (stLayout st) })

-------------------------------------------------------------------------------
-- Errors

-- | A text-related error emitted by the lexer or parser.
data LHsTextError
    = LexicalError    !LHsPos !Text         -- ^ A lexical error emitted by Alex.
    | UnclosedComment !LHsPos               -- ^ An unclosed multi-line comment error emitted by Alex.
    | ParseError      !LHsSpan !LHsToken    -- ^ A parse error emitted by Happy. 
                                            --   The first argument indicates where an unexpected token 
                                            --   starts and ends in the source.
    deriving (LHsTextError -> LHsTextError -> Bool
(LHsTextError -> LHsTextError -> Bool)
-> (LHsTextError -> LHsTextError -> Bool) -> Eq LHsTextError
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: LHsTextError -> LHsTextError -> Bool
== :: LHsTextError -> LHsTextError -> Bool
$c/= :: LHsTextError -> LHsTextError -> Bool
/= :: LHsTextError -> LHsTextError -> Bool
Eq, Int -> LHsTextError -> ShowS
[LHsTextError] -> ShowS
LHsTextError -> String
(Int -> LHsTextError -> ShowS)
-> (LHsTextError -> String)
-> ([LHsTextError] -> ShowS)
-> Show LHsTextError
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> LHsTextError -> ShowS
showsPrec :: Int -> LHsTextError -> ShowS
$cshow :: LHsTextError -> String
show :: LHsTextError -> String
$cshowList :: [LHsTextError] -> ShowS
showList :: [LHsTextError] -> ShowS
Show)

instance LHsError LHsTextError where
    buildError :: String -> LHsTextError -> Errata
buildError String
file (LexicalError LHsPos
pos Text
bad) =
        Maybe Text -> Block -> Maybe Text -> Errata
errataSimple
            (Text -> Maybe Text
forall a. a -> Maybe a
Just (Text
"Unexpected '" Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
bad Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
"'"))
            (String -> LHsSpan -> Text -> Block
underline String
file (LHsPos
pos LHsPos -> Int -> LHsSpan
+> Text -> Int
Text.length Text
bad) Text
"not sure how to interpret this symbol")
            Maybe Text
forall a. Maybe a
Nothing
    buildError String
file (UnclosedComment LHsPos
pos) =
        Maybe Text -> Block -> Maybe Text -> Errata
errataSimple
            (Text -> Maybe Text
forall a. a -> Maybe a
Just Text
"Unclosed comment")
            (String -> LHsSpan -> Text -> Block
underline String
file (LHsPos
pos LHsPos -> Int -> LHsSpan
+> Int
2) Text
"this comment is never closed")
            Maybe Text
forall a. Maybe a
Nothing
    buildError String
file (ParseError (LHsSpan LHsPos
start LHsPos
end) LHsToken
bad) =
        Maybe Text -> Block -> Maybe Text -> Errata
errataSimple
            (Text -> Maybe Text
forall a. a -> Maybe a
Just Text
"Parse error")
            -- Virtual tokens have an empty span, so we underline at least one character.
            (String -> LHsSpan -> Text -> Block
underline String
file (LHsPos -> LHsPos -> LHsSpan
LHsSpan LHsPos
start (LHsPos
end { posCol = max (posCol end) (posCol start + 1) })) Text
label)
            Maybe Text
forall a. Maybe a
Nothing
        where
            label :: Text
label = case LHsToken
bad of
                LHsToken
LHsTkVSemi  -> Text
"this starts a new declaration, but the previous one is unfinished"
                LHsToken
LHsTkVClose -> Text
"the block ends here, but something before it is unfinished"
                LHsToken
_           -> Text
"this was not expected here"