[project @ 2003-07-23 10:27:49 by wolfgang]
[ghc-base.git] / Text / Regex / Posix.hsc
1 -----------------------------------------------------------------------------
2 -- |
3 -- Module      :  Text.Regex.Posix
4 -- Copyright   :  (c) The University of Glasgow 2002
5 -- License     :  BSD-style (see the file libraries/base/LICENSE)
6 -- 
7 -- Maintainer  :  libraries@haskell.org
8 -- Stability   :  experimental
9 -- Portability :  non-portable (needs POSIX regexps)
10 --
11 -- Interface to the POSIX regular expression library.
12 --
13 -----------------------------------------------------------------------------
14
15 -- ToDo: should have an interface using PackedStrings.
16
17 module Text.Regex.Posix (
18         -- * The @Regex@ type
19         Regex,          -- abstract
20
21         -- * Compiling a regular expression
22         regcomp,        -- :: String -> Int -> IO Regex
23
24         -- ** Flags for regcomp
25         regExtended,    -- (flag to regcomp) use extended regex syntax
26         regIgnoreCase,  -- (flag to regcomp) ignore case when matching
27         regNewline,     -- (flag to regcomp) '.' doesn't match newline
28
29         -- * Matching a regular expression
30         regexec,        -- :: Regex                  -- pattern
31                         -- -> String                 -- string to match
32                         -- -> IO (Maybe (String,     -- everything before match
33                         --               String,     -- matched portion
34                         --               String,     -- everything after match
35                         --               [String]))  -- subexpression matches
36
37   ) where
38
39 #include <sys/types.h>
40 #include "regex.h"
41
42 import Prelude
43
44 import Foreign
45 import Foreign.C
46
47 -- | A compiled regular expression
48 newtype Regex = Regex (ForeignPtr CRegex)
49
50 -- -----------------------------------------------------------------------------
51 -- regcomp
52
53 -- | Compiles a regular expression
54 regcomp
55   :: String     -- ^ The regular expression to compile
56   -> Int        -- ^ Flags (summed together)
57   -> IO Regex   -- ^ Returns: the compiled regular expression
58 regcomp pattern flags = do
59   regex_fptr <- mallocForeignPtrBytes (#const sizeof(regex_t))
60   r <- withCString pattern $ \cstr ->
61          withForeignPtr regex_fptr $ \p ->
62            c_regcomp p cstr (fromIntegral flags)
63   addForeignPtrFinalizer regex_fptr ptr_regfree
64   if (r == 0)
65      then return (Regex regex_fptr)
66      else error "Text.Regex.Posix.regcomp: error in pattern" -- ToDo
67
68 -- -----------------------------------------------------------------------------
69 -- regexec
70
71 -- | Matches a regular expression against a string
72 regexec :: Regex                        -- ^ Compiled regular expression
73         -> String                       -- ^ String to match against
74         -> IO (Maybe (String, String, String, [String]))
75                 -- ^ Returns: 'Nothing' if the regex did not match the
76                 -- string, or:
77                 --
78                 -- @
79                 --   'Just' (everything before match,
80                 --         matched portion,
81                 --         everything after match,
82                 --         subexpression matches)
83                 -- @
84
85 regexec (Regex regex_fptr) str = do
86   withCString str $ \cstr -> do
87     withForeignPtr regex_fptr $ \regex_ptr -> do
88       nsub <- (#peek regex_t, re_nsub) regex_ptr
89       let nsub_int = fromIntegral (nsub :: CSize)
90       allocaBytes ((1 + nsub_int) * (#const sizeof(regmatch_t))) $ \p_match -> do
91                 -- add one because index zero covers the whole match
92         r <- c_regexec regex_ptr cstr (1 + nsub) p_match 0{-no flags for now-}
93
94         if (r /= 0) then return Nothing else do 
95
96         (before,match,after) <- matched_parts str p_match
97
98         sub_strs <- 
99           mapM (unpack str) $ take nsub_int $ tail $
100              iterate (`plusPtr` (#const sizeof(regmatch_t))) p_match
101
102         return (Just (before, match, after, sub_strs))
103
104 matched_parts :: String -> Ptr CRegMatch -> IO (String, String, String)
105 matched_parts string p_match = do
106   start <- (#peek regmatch_t, rm_so) p_match :: IO (#type regoff_t)
107   end   <- (#peek regmatch_t, rm_eo) p_match :: IO (#type regoff_t)
108   let s = fromIntegral start; e = fromIntegral end
109   return ( take s string, 
110            take (e-s) (drop s string),
111            drop e string )  
112
113 unpack :: String -> Ptr CRegMatch -> IO (String)
114 unpack string p_match = do
115   start <- (#peek regmatch_t, rm_so) p_match :: IO (#type regoff_t)
116   end   <- (#peek regmatch_t, rm_eo) p_match :: IO (#type regoff_t)
117   -- the subexpression may not have matched at all, perhaps because it
118   -- was optional.  In this case, the offsets are set to -1.
119   if (start == -1) then return "" else do
120   return (take (fromIntegral (end-start)) (drop (fromIntegral start) string))
121
122 -- -----------------------------------------------------------------------------
123 -- The POSIX regex C interface
124
125 -- Flags for regexec
126 #enum Int,, \
127         REG_NOTBOL, \
128         REG_NOTEOL
129
130 -- Return values from regexec
131 #enum Int,, \
132         REG_NOMATCH
133 --      REG_ESPACE
134
135 -- Flags for regcomp
136 #enum Int,, \
137         REG_EXTENDED, \
138         regIgnoreCase = REG_ICASE, \
139         REG_NOSUB, \
140         REG_NEWLINE
141
142 -- Error codes from regcomp
143 #enum Int,, \
144         REG_BADBR, \
145         REG_BADPAT, \
146         REG_BADRPT, \
147         REG_ECOLLATE, \
148         REG_ECTYPE, \
149         REG_EESCAPE, \
150         REG_ESUBREG, \
151         REG_EBRACK, \
152         REG_EPAREN, \
153         REG_EBRACE, \
154         REG_ERANGE, \
155         REG_ESPACE
156
157 type CRegex    = ()
158 type CRegMatch = ()
159
160 foreign import ccall unsafe "regcomp"
161   c_regcomp :: Ptr CRegex -> CString -> CInt -> IO CInt
162
163 foreign import ccall  unsafe "&regfree"
164   ptr_regfree :: FunPtr (Ptr CRegex -> IO ())
165
166 foreign import ccall unsafe "regexec"
167   c_regexec :: Ptr CRegex -> CString -> CSize
168             -> Ptr CRegMatch -> CInt -> IO CInt