Debian Codegraph @

Text/RE/ZeInternals/Types/CaptureID.hs

raw
1 {-# LANGUAGE GeneralizedNewtypeDeriving #-}
2
3 module Text.RE.ZeInternals.Types.CaptureID where
4
5 import qualified Data.HashMap.Strict as HMS
6 import Data.Hashable
7 import Data.Ix
8 import qualified Data.Text as T
9
10
11 -- | CaptureID identifies captures, either by number
12 -- (e.g., [cp|1|]) or name (e.g., [cp|foo|]).
13 data CaptureID
14 = IsCaptureOrdinal CaptureOrdinal -- [cp|3|]
15 | IsCaptureName CaptureName -- [cp|y|]
16 deriving (Show,Ord,Eq)
17
18 -- | the dictionary for named captures stored in compiled regular
19 -- expressions associates
20 type CaptureNames = HMS.HashMap CaptureName CaptureOrdinal
21
22 -- | an empty 'CaptureNames' dictionary
23 noCaptureNames :: CaptureNames
24 noCaptureNames = HMS.empty
25
26 -- | a 'CaptureName' is just the text of the name
27 newtype CaptureName = CaptureName { getCaptureName :: T.Text }
28 deriving (Show,Ord,Eq)
29
30 instance Hashable CaptureName where
31 hashWithSalt i = hashWithSalt i . getCaptureName
32
33 -- | a 'CaptureOrdinal' is just the number of the capture, starting
34 -- with 0 for the whole of the text matched, then in leftmost,
35 -- outermost
36 newtype CaptureOrdinal = CaptureOrdinal { getCaptureOrdinal :: Int }
37 deriving (Show,Ord,Eq,Enum,Ix,Num)
38
39 -- | look up a 'CaptureID' in the 'CaptureNames' dictionary
40 findCaptureID :: CaptureID -> CaptureNames -> Either String CaptureOrdinal
41 findCaptureID (IsCaptureOrdinal o) _ = Right o
42 findCaptureID (IsCaptureName n) hms =
43 maybe oops Right $ HMS.lookup n hms
44 where
45 oops = Left $ unlines $
46 ("lookupCaptureID: " ++ T.unpack t ++ " not found in:") :
47 [ " "++T.unpack (getCaptureName nm) | nm <- HMS.keys hms ]
48 t = getCaptureName n