%  Copyright (C) 2003 David Roundy
%
%  This program is free software; you can redistribute it and/or modify
%  it under the terms of the GNU General Public License as published by
%  the Free Software Foundation; either version 2, or (at your option)
%  any later version.
%
%  This program 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 General Public License for more details.
%
%  You should have received a copy of the GNU General Public License
%  along with this program; see the file COPYING.  If not, write to
%  the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
%  Boston, MA 02110-1301, USA.


\begin{code}
module RegChars ( regChars,
                ) where

(&&&) :: (a -> Bool) -> (a -> Bool) -> (a -> Bool)
(&&&) a b c = a c && b c

(|||) :: (a -> Bool) -> (a -> Bool) -> (a -> Bool)
(|||) a b c = a c || b c

{-# INLINE regChars #-}
regChars :: String -> (Char -> Bool)
regChars ('^':cs) = not . normalRegChars (unescapeChars cs)
regChars ('\\':'^':cs) = normalRegChars $ unescapeChars $ '^':cs
regChars cs = normalRegChars $ unescapeChars cs

{-# INLINE unescapeChars #-}
unescapeChars :: String -> String
unescapeChars ('\\':'n':cs) = '\n' : unescapeChars cs
unescapeChars ('\\':'t':cs) = '\t' : unescapeChars cs
unescapeChars ('\\':'^':cs) = '^' : unescapeChars cs
unescapeChars (c:cs) = c : unescapeChars cs
unescapeChars [] = []

{-# INLINE normalRegChars #-}
normalRegChars :: String -> (Char -> Bool)
normalRegChars ('\\':'.':cs) = (=='.') ||| normalRegChars cs
normalRegChars ('\\':'-':cs) = (=='-') ||| normalRegChars cs
normalRegChars ('\\':'\\':cs) = (=='\\') ||| normalRegChars cs
normalRegChars ('\\':c:_) = error $ "'\\"++[c]++"' not supported."
normalRegChars (c1:'-':c2:cs) = ((>= c1) &&& (<= c2)) ||| normalRegChars cs
normalRegChars (c:cs) = (== c) ||| normalRegChars cs
normalRegChars [] = \_ -> False
\end{code}


