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