module Arithmetic.Parser where

import Control.Applicative
import Text.Trifecta
import Arithmetic.Model

booleanValue :: Parser Term
booleanValue =
  token
      ((string "true"  >> return TmTrue)
  <|> (string "false" >> return TmFalse))

zeroValue :: Parser Term
zeroValue = token $ char '0' >> return TmZero

iszero :: Parser Term
iszero = TmIsZero <$> token (string "iszero" >> expression)

succesor :: Parser Term
succesor = TmSucc <$> token (string "succ" >> expression)

predecesor :: Parser Term
predecesor = TmPred <$> token (string "pred" >> expression)

ifStatement :: Parser Term
ifStatement = do
  token $ string "if"
  condition <- expression
  token $ string "then"
  trueBranch <- expression
  token $ string "else"
  falseBranch <- expression
  return $ TmIf condition trueBranch falseBranch

expression :: Parser Term
expression =
  token
      ((char '(' >> inner <* char ')')
  <|> inner)
  where inner =
              booleanValue
          <|> zeroValue
          <|> iszero
          <|> succesor
          <|> predecesor
          <|> ifStatement
