\begin{code}
module Text.RE.ZeInternals.Replace
(
REContext(..)
, RELocation(..)
, isTopLocation
, replaceAll
, replaceAllCaptures
, replaceAllCaptures_
, replaceAllCapturesM
, replace
, replaceCaptures
, replaceCaptures_
, replaceCapturesM
, expandMacros
, expandMacros'
, templateCaptures
, Replace(..)
, ReplaceMethods(..)
, replaceMethods
) where
import Control.Applicative
import Data.Array
import qualified Data.ByteString.Char8 as B
import qualified Data.ByteString.Lazy.Char8 as LBS
import Data.Char
import qualified Data.Foldable as F
import Data.Functor.Identity
import qualified Data.HashMap.Strict as HM
import Data.Maybe
import Data.Monoid
import qualified Data.Sequence as S
import qualified Data.Text as T
import qualified Data.Text.Encoding as TE
import qualified Data.Text.Lazy as LT
import Prelude.Compat
import Text.RE.REOptions
import Text.RE.ZeInternals.Types.Capture
import Text.RE.ZeInternals.Types.CaptureID
import Text.RE.ZeInternals.Types.Match
import Text.RE.ZeInternals.Types.Matches
import Text.Read
import Text.Regex.TDFA
import Text.Regex.TDFA.Text()
import Text.Regex.TDFA.Text.Lazy()
\end{code}
ReContext and RELocation
------------------------
\begin{code}
data REContext
= TOP
| SUB
| ALL
deriving (Show)
data RELocation =
RELocation
{ locationMatch :: Int
, locationCapture :: CaptureOrdinal
}
deriving (Show)
\end{code}
\begin{code}
isTopLocation :: RELocation -> Bool
isTopLocation = (==0) . locationCapture
\end{code}
\begin{code}
replaceAll :: Replace a
=> a
-> Matches a
-> a
replaceAll tpl ac = replaceAllCaptures TOP (parseTemplateR tpl) ac
\end{code}
\begin{code}
replaceAllCaptures :: Replace a
=> REContext
-> (Match a->RELocation->Capture a->Maybe a)
-> Matches a
-> a
\end{code}
\begin{code}
replaceAllCaptures = replaceAllCaptures_ replaceMethods
\end{code}
\begin{code}
replaceAllCaptures_ :: Extract a
=> ReplaceMethods a
-> REContext
-> (Match a->RELocation->Capture a->Maybe a)
-> Matches a
-> a
replaceAllCaptures_ s ctx phi ac =
runIdentity $ replaceAllCapturesM s ctx (lift_phi phi) ac
\end{code}
\begin{code}
replaceAllCapturesM :: (Extract a,Monad m)
=> ReplaceMethods a
-> REContext
-> (Match a->RELocation->Capture a->m (Maybe a))
-> Matches a
-> m a
replaceAllCapturesM r ctx phi_ Matches{..} =
replaceCapturesM r ALL phi $ Match matchesSource cnms arr
where
phi _ (RELocation _ i) = case arr_c!i of
Just caps -> phi_ caps . uncurry RELocation $ arr_i ! i
Nothing -> const $ return Nothing
arr_c = listArray bds $
concat $
[ repl (rangeSize $ bounds $ matchArray cs) cs
| cs <- allMatches
]
arr_i = listArray bds j_ks
arr = listArray bds $
[ arr_ ! k
| arr_ <- map matchArray allMatches
, k <- indices arr_
]
bds = (0,CaptureOrdinal $ length j_ks1)
j_ks =
[ (j,k)
| (j,arr_) <- zip [0..] $ map matchArray allMatches
, k <- indices arr_
]
repl 0 _ = []
repl n x = case ctx of
TOP -> Just x : replicate (n1) Nothing
SUB -> Nothing : replicate (n1) (Just x)
ALL -> replicate n $ Just x
cnms = fromMaybe noCaptureNames $ listToMaybe $ map captureNames allMatches
\end{code}
\begin{code}
replace :: Replace a
=> a
-> Match a
-> a
replace tpl c = replaceCaptures TOP (parseTemplateR tpl) c
\end{code}
\begin{code}
replaceCaptures :: Replace a
=> REContext
-> (Match a->RELocation->Capture a->Maybe a)
-> Match a
-> a
replaceCaptures = replaceCaptures_ replaceMethods
\end{code}
\begin{code}
replaceCaptures_ :: Extract a
=> ReplaceMethods a
-> REContext
-> (Match a->RELocation->Capture a->Maybe a)
-> Match a
-> a
replaceCaptures_ s ctx phi caps =
runIdentity $ replaceCapturesM s ctx (lift_phi phi) caps
\end{code}
\begin{code}
replaceCapturesM :: (Monad m,Extract a)
=> ReplaceMethods a
-> REContext
-> (Match a->RELocation->Capture a->m (Maybe a))
-> Match a
-> m a
replaceCapturesM ReplaceMethods{..} ctx phi_ caps@Match{..} = do
(hay',_) <- foldr sc (return (matchSource,[])) $
zip [0..] $ elems matchArray
return hay'
where
sc (i,cap0) act = do
(hay,ds) <- act
let ndl = capturedText cap
cap = adj hay ds cap0
mb <- phi i cap
case mb of
Nothing -> return (hay,ds)
Just ndl' ->
return
( methodSubst (const ndl') cap
, (captureOffset cap,len'len) : ds
)
where
len' = methodLength ndl'
len = methodLength ndl
adj hay ds cap =
Capture
{ captureSource = hay
, capturedText = before len $ after off0 hay
, captureOffset = off0
, captureLength = len
}
where
len = len0 + sum
[ delta
| (off,delta) <- ds
, off < off0 + len0
]
len0 = captureLength cap
off0 = captureOffset cap
phi i cap = case ctx of
TOP | i/=0 -> return Nothing
SUB | i==0 ->return Nothing
_ ->
case not $ hasCaptured cap of
True -> return Nothing
False -> phi_ caps (RELocation 0 i) cap
\end{code}
expandMacros
------------
\begin{code}
expandMacros :: (r->String) -> Macros r -> String -> String
expandMacros x_src hm s =
case HM.null hm of
True -> s
False -> expandMacros' (fmap x_src . flip HM.lookup hm) s
\end{code}
\begin{code}
expandMacros' :: (MacroID->Maybe String) -> String -> String
expandMacros' lu = fixpoint e_m
where
e_m re_s = replaceAllCaptures TOP phi $ re_s $=~ "@(@|\\{([^{}]+)\\})"
where
phi mtch _ cap = case txt == "@@" of
True -> Just "@"
False -> Just $ fromMaybe txt $ lu ide
where
txt = capturedText cap
ide = MacroID $ capturedText $ capture c2 mtch
c2 = IsCaptureOrdinal $ CaptureOrdinal 2
\end{code}
\begin{code}
lift_phi :: Monad m
=> (Match a->RELocation->Capture a->Maybe a)
-> (Match a->RELocation->Capture a->m (Maybe a))
lift_phi phi_ = phi
where
phi caps' loc' cap' = return $ phi_ caps' loc' cap'
\end{code}
templateCaptures
----------------
\begin{code}
templateCaptures :: ( Replace a
, RegexContext Regex a (Matches a)
, RegexMaker Regex CompOption ExecOption String
)
=> (a->String)
-> a
-> [CaptureID]
templateCaptures unpack tpl =
[ cid
| mtch <- allMatches $ scan_template tpl
, Right cid <- [parse_template_capture unpack mtch]
]
parse_template_capture :: (a->String) -> Match a -> Either a CaptureID
parse_template_capture unpack t_mtch = case t_mtch !$? c2 of
Just cap -> case readMaybe stg of
Nothing -> Right $ IsCaptureName $ CaptureName $ T.pack stg
Just cn -> Right $ IsCaptureOrdinal $ CaptureOrdinal cn
where
stg = unpack $ capturedText cap
Nothing -> case s == "$" of
True -> Left t
False -> Right $ IsCaptureOrdinal $ CaptureOrdinal $ read s
where
s = unpack t
t = capturedText $ capture c1 t_mtch
c1 = IsCaptureOrdinal $ CaptureOrdinal 1
c2 = IsCaptureOrdinal $ CaptureOrdinal 2
scan_template :: ( Replace a
, RegexContext Regex a (Matches a)
, RegexMaker Regex CompOption ExecOption String
)
=> a
-> Matches a
scan_template tpl = tpl $=~ "\\$(\\$|[0-9]|\\{([^{}]+)\\})"
\end{code}
Replace and ReplaceMethods
--------------------------
\begin{code}
class (Show a,Eq a,Ord a,Extract a,Monoid a) => Replace a where
lengthR :: a -> Int
packR :: String -> a
unpackR :: a -> String
textifyR :: a -> T.Text
detextifyR :: T.Text -> a
linesR :: a -> [a]
unlinesR :: [a] -> a
appendNewlineR :: a -> a
substR :: (a->a) -> Capture a -> a
parseTemplateR :: a -> Match a -> RELocation -> Capture a -> Maybe a
textifyR = T.pack . unpackR
detextifyR = packR . T.unpack
appendNewlineR = (<> packR "\n")
substR f m@Capture{..} =
capturePrefix m <> f capturedText <> captureSuffix m
\end{code}
\begin{code}
data ReplaceMethods a =
ReplaceMethods
{ methodLength :: a -> Int
, methodSubst :: (a->a) -> Capture a -> a
}
replaceMethods :: Replace a => ReplaceMethods a
replaceMethods =
ReplaceMethods
{ methodLength = lengthR
, methodSubst = substR
}
\end{code}
The Replace Instances
---------------------
\begin{code}
instance Replace [Char] where
lengthR = length
packR = id
unpackR = id
textifyR = T.pack
detextifyR = T.unpack
linesR = lines
unlinesR = unlines
appendNewlineR = (<>"\n")
parseTemplateR = parseTemplateR' id
instance Replace B.ByteString where
lengthR = B.length
packR = B.pack
unpackR = B.unpack
textifyR = TE.decodeUtf8
detextifyR = TE.encodeUtf8
linesR = B.lines
unlinesR = B.unlines
appendNewlineR = (<>"\n")
parseTemplateR = parseTemplateR' B.unpack
instance Replace LBS.ByteString where
lengthR = fromEnum . LBS.length
packR = LBS.pack
unpackR = LBS.unpack
textifyR = TE.decodeUtf8 . LBS.toStrict
linesR = LBS.lines
unlinesR = LBS.unlines
detextifyR = LBS.fromStrict . TE.encodeUtf8
appendNewlineR = (<>"\n")
parseTemplateR = parseTemplateR' LBS.unpack
instance Replace (S.Seq Char) where
lengthR = S.length
packR = S.fromList
unpackR = F.toList
linesR = map packR . lines . unpackR
unlinesR = packR . unlines . map unpackR
parseTemplateR = parseTemplateR' F.toList
instance Replace T.Text where
lengthR = T.length
packR = T.pack
unpackR = T.unpack
textifyR = id
detextifyR = id
linesR = T.lines
unlinesR = T.unlines
appendNewlineR = (<>"\n")
parseTemplateR = parseTemplateR' T.unpack
instance Replace LT.Text where
lengthR = fromEnum . LT.length
packR = LT.pack
unpackR = LT.unpack
textifyR = LT.toStrict
detextifyR = LT.fromStrict
linesR = LT.lines
unlinesR = LT.unlines
appendNewlineR = (<>"\n")
parseTemplateR = parseTemplateR' LT.unpack
\end{code}
Parsing Replace Templates
-------------------------
\begin{code}
parseTemplateR' :: ( Replace a
, RegexContext Regex a (Matches a)
, RegexMaker Regex CompOption ExecOption String
)
=> (a->String)
-> a
-> Match a
-> RELocation
-> Capture a
-> Maybe a
parseTemplateR' unpack tpl mtch _ _ =
Just $ replaceAllCaptures TOP phi $ scan_template tpl
where
phi t_mtch _ _ = either Just this $ parse_template_capture unpack t_mtch
this cid = capturedText <$> mtch !$? cid
\end{code}
Helpers
-------
\begin{code}
fixpoint :: (Eq a) => (a->a) -> a -> a
fixpoint f = chk . iterate f
where
chk (x:x':_) | x==x' = x
chk xs = chk $ tail xs
\end{code}
\begin{code}
($=~) :: ( RegexContext Regex source target
, RegexMaker Regex CompOption ExecOption String
)
=> source -> String -> target
($=~) = (=~)
\end{code}