{-  Copyright 2010 Dominique Devriese

    This file is part of the grammar-combinators library.

    The grammar-combinators library is free software: you can
    redistribute it and/or modify it under the terms of the GNU
    Lesser General Public License as published by the Free
    Software Foundation, either version 3 of the License, or (at
    your option) any later version.

    Foobar is distributed in the hope that it will be useful, but
    WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    GNU Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General
    Public License along with Foobar. If not, see
    <http://www.gnu.org/licenses/>.
-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE ScopedTypeVariables #-}

-- | Compatibility component for the Parsec library.
module Text.GrammarCombinators.Parser.Parsec (
  parseParsec
  ) where

import Text.GrammarCombinators.Base
import Text.GrammarCombinators.Transform.UnfoldRecursion

import Text.Parsec
import Text.Parsec.Pos
import qualified Text.Parsec as Parsec
--import Text.ParserCombinators.Parsec.Prim

newtype WrapGenParser t v = WGP { unWGP :: Parsec [ConcreteToken t] () v }

instance (Token t) => ProductionRule (WrapGenParser t) where
  a >>> b = WGP $ do f <- unWGP a; x <- unWGP b; return $ f x
  a ||| b = WGP $ try (unWGP a) <|> unWGP b
  endOfInput = WGP eof
  die = WGP parserZero

instance (Token t) => EpsProductionRule (WrapGenParser t) where
  epsilon v = WGP $ return v

instance (Token t) => LiftableProductionRule (WrapGenParser t) where
  epsilonL v _ = epsilon v

instance (Token t) => TokenProductionRule (WrapGenParser t) t where
  token tt = WGP $ tokenPrim show nextPos testToken
    where
      testToken t        = if classify t == tt then Just t else Nothing
      nextPos p _ _  = newPos (sourceName p) (sourceLine p) (sourceColumn p+1)

-- | Parse a given string according to a given grammar, starting from a given start
--   non-terminal, using the Parsec parser library. Currently uses backtracking for
--   every branch.
--  
--   It is probably possible to automatically approximate 
--   branches where backtracking is required, which would be neat and really go beyond
--   what is currently possible in Parsec. Help welcome!
parseParsec :: forall phi t r ix.
               (Token t) =>
               ProcessingContextFreeGrammar phi t r ->
               phi ix -> SourceName -> [ConcreteToken t] -> Either ParseError (r ix)
parseParsec gram idx = 
  let irule :: WrapGenParser t (r ix)
      irule = unfoldRecursion gram idx
      parser = unWGP irule
  in Parsec.parse parser