4 ParserM(..), AlexInput, run_parser,
7 StartCode, start_code, set_start_code,
8 inc_brace_depth, dec_brace_depth,
12 Action, andBegin, mkT, mkTv,
16 alexGetChar, alexInputPrevChar, input, position,
22 newtype ParserM a = ParserM (AlexInput -> St -> Either String (AlexInput, St, a))
24 instance Monad ParserM where
25 ParserM m >>= k = ParserM $ \i s -> case m i s of
31 return a = ParserM $ \i s -> Right (i, s, a)
32 fail err = ParserM $ \_ _ -> Left err
34 run_parser :: ParserM a -> (String -> Either String a)
35 run_parser (ParserM f)
36 = \s -> case f (AlexInput init_pos s) init_state of
38 Right (_, _, x) -> Right x
43 start_code :: !StartCode,
88 type Action = String -> ParserM Token
90 set_start_code :: StartCode -> ParserM ()
91 set_start_code sc = ParserM $ \i st -> Right (i, st { start_code = sc }, ())
93 inc_brace_depth :: ParserM ()
94 inc_brace_depth = ParserM $ \i st ->
95 Right (i, st { brace_depth = brace_depth st + 1 }, ())
97 dec_brace_depth :: ParserM ()
98 dec_brace_depth = ParserM $ \i st ->
99 let bd = brace_depth st - 1
100 sc = if bd == 0 then 0 else 1
101 in Right (i, st { brace_depth = bd, start_code = sc }, ())
103 andBegin :: Action -> StartCode -> Action
104 (act `andBegin` sc) x = do set_start_code sc
107 mkT :: Token -> Action
108 mkT t = mkTv (const t)
110 mkTv :: (String -> Token) -> Action
111 mkTv f str = ParserM (\i st -> Right (i, st, f str))
115 data Pos = Pos !Int{- Line -} !Int{- Column -}
117 get_pos :: ParserM Pos
118 get_pos = ParserM $ \i@(AlexInput p _) st -> Right (i, st, p)
120 alexMove :: Pos -> Char -> Pos
121 alexMove (Pos l _) '\n' = Pos (l+1) 1
122 alexMove (Pos l c) '\t' = Pos l ((c+8) `div` 8 * 8)
123 alexMove (Pos l c) _ = Pos l (c+1)
128 show_pos :: Pos -> String
129 show_pos (Pos l c) = "line " ++ show l ++ ", column " ++ show c
133 data AlexInput = AlexInput {position :: !Pos, input :: String}
135 alexGetChar :: AlexInput -> Maybe (Char,AlexInput)
136 alexGetChar (AlexInput p (x:xs)) = Just (x, AlexInput (alexMove p x) xs)
137 alexGetChar (AlexInput _ []) = Nothing
139 alexInputPrevChar :: AlexInput -> Char
140 alexInputPrevChar _ = error "Lexer doesn't implement alexInputPrevChar"
142 happyError :: ParserM a
143 happyError = do p <- get_pos
144 fail $ "Parse error at " ++ show_pos p