0647cf35feddc24f90b2e40ddfe28c4967d5bb6a
[ghc-hetmet.git] / ghc / compiler / utils / StringBuffer.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1997
3 %
4 \section{String buffers}
5
6 Buffers for scanning string input stored in external arrays.
7
8 \begin{code}
9 #include "HsVersions.h"
10
11 module StringBuffer
12        (
13         StringBuffer,
14
15          -- creation
16         hGetStringBuffer,  -- :: FilePath       -> IO StringBuffer
17         freeStringBuffer,  -- :: StringBuffer   -> IO ()
18
19          -- Lookup
20         currentChar,      -- :: StringBuffer -> Char
21         currentChar#,     -- :: StringBuffer -> Char#
22         indexSBuffer,     -- :: StringBuffer -> Int -> Char
23         indexSBuffer#,    -- :: StringBuffer -> Int# -> Char#
24          -- relative lookup, i.e, currentChar = lookAhead 0
25         lookAhead,        -- :: StringBuffer -> Int  -> Char
26         lookAhead#,       -- :: StringBuffer -> Int# -> Char#
27         
28          -- moving the end point of the current lexeme.
29         setCurrentPos#,   -- :: StringBuffer -> Int# -> StringBuffer
30         incLexeme,        -- :: StringBuffer -> StringBuffer
31         decLexeme,        -- :: StringBuffer -> StringBuffer
32
33          -- move the start and end lexeme pointer on by x units.        
34         stepOn,           -- :: StringBuffer -> StringBuffer
35         stepOnBy#,        -- :: StringBuffer -> Int# -> StringBuffer
36         stepOnTo#,        -- :: StringBuffer -> Int# -> StringBuffer
37         stepOnUntil,      -- :: (Char -> Bool) -> StringBuffer -> StringBuffer
38         stepOverLexeme,   -- :: StringBuffer   -> StringBuffer
39         scanNumLit,       -- :: Int -> StringBuffer -> (Int, StringBuffer)
40         expandWhile,      -- :: (Char -> Bool) -> StringBuffer -> StringBuffer
41         expandUntilMatch, -- :: StrinBuffer -> String -> StringBuffer
42          -- at or beyond end of buffer?
43         bufferExhausted,  -- :: StringBuffer -> Bool
44         emptyLexeme,      -- :: StringBuffer -> Bool
45
46          -- matching
47         prefixMatch,       -- :: StringBuffer -> String -> Bool
48         untilEndOfString#, -- :: StringBuffer -> Int#
49         untilEndOfChar#,   -- :: StringBuffer -> Int#
50         untilChar#,        -- :: StringBuffer -> Char# -> Int#
51
52          -- conversion
53         lexemeToString,     -- :: StringBuffer -> String
54         lexemeToByteArray,  -- :: StringBuffer -> _ByteArray Int
55         lexemeToFastString, -- :: StringBuffer -> FastString
56         lexemeToBuffer,     -- :: StringBuffer -> StringBuffer
57
58         FastString,
59         _ByteArray
60        ) where
61
62 #if __GLASGOW_HASKELL__ <= 200
63 import PreludeGlaST
64 import PreludeGlaMisc
65 import HandleHack
66 import Ubiq
67 #else
68 import GlaExts
69 import Foreign
70 import IOBase
71 import IOHandle
72 import ST
73 import STBase
74 import Char (isDigit)
75 # if __GLASGOW_HASKELL__ == 202
76 import PrelBase ( Char(..) )
77 # endif
78 #endif
79 import PrimPacked
80 import FastString
81
82 \end{code} 
83
84 \begin{code}
85 data StringBuffer
86  = StringBuffer
87      Addr#
88 --     ForeignObj#  -- the data
89      Int#         -- length
90      Int#         -- lexeme start
91      Int#         -- current pos
92 \end{code}
93
94 \begin{code}
95 instance Text StringBuffer where
96         showsPrec _ s = showString ""
97 \end{code}
98
99 \begin{code}
100 hGetStringBuffer :: FilePath -> IO StringBuffer
101 hGetStringBuffer fname =
102 --    trace ("Renamer: opening " ++ fname) $
103     openFile fname ReadMode >>= \ hndl ->
104     hFileSize hndl          >>= \ len@(J# _ _ d#) ->
105     let len_i = fromInteger len in
106       -- Allocate an array for system call to store its bytes into.
107       -- ToDo: make it robust
108 --    trace (show ((len_i::Int)+1)) $
109     (_casm_ `` %r=(char *)malloc(sizeof(char)*(int)%0); '' (len_i::Int))  `CCALL_THEN` \ arr@(A# a#) ->
110     if addr2Int# a# ==# 0# then
111        failWith MkIOError(hndl,UserError,("hGetStringBuffer: Could not allocate "++show len_i ++ " bytes"))
112     else
113
114 --   _casm_ `` %r=NULL; ''                                   `thenPrimIO` \ free_p ->
115 --    makeForeignObj arr free_p                              `thenPrimIO` \ fo@(_ForeignObj fo#) ->
116      _readHandle hndl        >>= \ hndl_ ->
117      _writeHandle hndl hndl_ >>
118      let ptr = _filePtr hndl_ in
119      _ccall_ fread arr (1::Int) len_i ptr                     `CCALL_THEN` \  (I# read#) ->
120 --     trace ("DEBUG: opened " ++ fname ++ show (I# read#)) $
121      hClose hndl                     >>
122      if read# ==# 0# then -- EOF or other error
123         failWith MkIOError(hndl,UserError,"hGetStringBuffer: EOF reached or some other error")
124      else
125         -- Add a sentinel NUL
126         _casm_ `` ((char *)%0)[(int)%1]=(char)0; '' arr (I# (read# -# 1#)) `CCALL_THEN` \ () ->
127         return (StringBuffer a# read# 0# 0#)
128
129 freeStringBuffer :: StringBuffer -> IO ()
130 freeStringBuffer (StringBuffer a# _ _ _) =
131  _casm_ `` free((char *)%0); '' (A# a#) `CCALL_THEN` \ () ->
132  return ()
133
134 unsafeWriteBuffer :: StringBuffer -> Int# -> Char# -> StringBuffer
135 unsafeWriteBuffer s@(StringBuffer a _ _ _) i# ch# =
136  unsafePerformPrimIO (
137    _casm_ `` ((char *)%0)[(int)%1]=(char)%2; '' (A# a) (I# i#) (C# ch#) `thenPrimIO` \ () ->
138    returnPrimIO s)
139
140 \end{code}
141
142 Lookup
143
144 \begin{code}
145 currentChar# :: StringBuffer -> Char#
146 currentChar# (StringBuffer fo# _ _ current#) = indexCharOffAddr# fo# current#
147
148 currentChar  :: StringBuffer -> Char
149 currentChar sb = case currentChar# sb of c -> C# c
150
151 indexSBuffer# :: StringBuffer -> Int# -> Char#
152 indexSBuffer# (StringBuffer fo# _ _ _) i# = indexCharOffAddr# fo# i#
153
154 indexSBuffer :: StringBuffer -> Int -> Char
155 indexSBuffer sb (I# i#) = case indexSBuffer# sb i# of c -> C# c
156
157  -- relative lookup, i.e, currentChar = lookAhead 0
158 lookAhead# :: StringBuffer -> Int# -> Char#
159 lookAhead# (StringBuffer fo# _ _ c#) i# = indexCharOffAddr# fo# (c# +# i#)
160
161 lookAhead :: StringBuffer -> Int  -> Char
162 lookAhead sb (I# i#) = case lookAhead# sb i# of c -> C# c
163
164 \end{code}
165
166  moving the start point of the current lexeme.
167
168 \begin{code}
169  -- moving the end point of the current lexeme.
170 setCurrentPos# :: StringBuffer -> Int# -> StringBuffer
171 setCurrentPos# (StringBuffer fo l# s# c#) i# =
172  StringBuffer fo l# s# (c# +# i#)
173
174 -- augmenting the current lexeme by one.
175 incLexeme :: StringBuffer -> StringBuffer
176 incLexeme (StringBuffer fo l# s# c#) = StringBuffer fo l# s# (c# +# 1#)
177
178 decLexeme :: StringBuffer -> StringBuffer
179 decLexeme (StringBuffer fo l# s# c#) = StringBuffer fo l# s# (c# -# 1#)
180
181 \end{code}
182
183 -- move the start and end point of the buffer on by
184 -- x units.        
185
186 \begin{code}
187 stepOn :: StringBuffer -> StringBuffer
188 stepOn (StringBuffer fo l# s# c#) = StringBuffer fo l# (s# +# 1#) (s# +# 1#) -- assume they're the same.
189
190 stepOnBy# :: StringBuffer -> Int# -> StringBuffer
191 stepOnBy# (StringBuffer fo# l# s# c#) i# = 
192  case s# +# i# of
193   new_s# -> StringBuffer fo# l# new_s# new_s#
194
195 -- jump to pos.
196 stepOnTo# :: StringBuffer -> Int# -> StringBuffer
197 stepOnTo# (StringBuffer fo l _ _) s# = StringBuffer fo l s# s#
198
199 stepOnUntil :: (Char -> Bool) -> StringBuffer -> StringBuffer
200 stepOnUntil pred (StringBuffer fo l# s# c#) =
201  loop c#
202   where
203    loop c# = 
204     case indexCharOffAddr# fo c# of
205      ch# | pred (C# ch#) -> StringBuffer fo l# c# c#
206          | ch# `eqChar#` '\NUL'# && c# >=# l# -> StringBuffer fo l# l# l# -- EOB, return immediately.
207          | otherwise     -> loop (c# +# 1#)
208
209 stepOverLexeme :: StringBuffer -> StringBuffer
210 stepOverLexeme (StringBuffer fo l s# c#) = StringBuffer fo l c# c#
211
212 expandWhile :: (Char -> Bool) -> StringBuffer -> StringBuffer
213 expandWhile pred (StringBuffer fo l# s# c#) =
214  loop c#
215   where
216    loop c# = 
217     case indexCharOffAddr# fo c# of
218      ch# | pred (C# ch#) -> loop (c# +# 1#)
219          | ch# `eqChar#` '\NUL'# && c# >=# l# -> StringBuffer fo l# l# l# -- EOB, return immediately.
220          | otherwise     -> StringBuffer fo l# s# c#
221
222
223 scanNumLit :: Int -> StringBuffer -> (Int,StringBuffer)
224 scanNumLit (I# acc#) (StringBuffer fo l# s# c#) =
225  loop acc# c#
226   where
227    loop acc# c# = 
228     case indexCharOffAddr# fo c# of
229      ch# | isDigit (C# ch#) -> loop (acc# *# 10# +# (ord# ch# -# ord# '0'#)) (c# +# 1#)
230          | ch# `eqChar#` '\NUL'# && c# >=# l# -> (I# acc#, StringBuffer fo l# l# l#) -- EOB, return immediately.
231          | otherwise        -> (I# acc#,StringBuffer fo l# s# c#)
232
233
234 expandUntilMatch :: StringBuffer -> String -> StringBuffer
235 expandUntilMatch (StringBuffer fo l# s# c#) str =
236   loop c# str
237   where
238    loop c# [] = StringBuffer fo l# s# c#
239    loop c# ((C# x#):xs) =
240      if indexCharOffAddr# fo c# `eqChar#` x# then
241         loop (c# +# 1#) xs
242      else
243         loop (c# +# 1#) str
244 \end{code}
245
246 \begin{code}
247    -- at or beyond end of buffer?
248 bufferExhausted :: StringBuffer -> Bool
249 bufferExhausted (StringBuffer fo l# _ c#) = c# >=# l#
250
251 emptyLexeme :: StringBuffer -> Bool
252 emptyLexeme (StringBuffer fo l# s# c#) = s# ==# c#
253
254  -- matching
255 prefixMatch :: StringBuffer -> String -> Maybe StringBuffer
256 prefixMatch (StringBuffer fo l# s# c#) str =
257   loop c# str
258   where
259    loop c# [] = Just (StringBuffer fo l# s# c#)
260    loop c# ((C# x#):xs) =
261      if indexCharOffAddr# fo c# `eqChar#` x# then
262         loop (c# +# 1#) xs
263      else
264         Nothing
265
266 untilEndOfString# :: StringBuffer -> StringBuffer
267 untilEndOfString# (StringBuffer fo l# s# c#) = 
268  loop c# 
269  where
270   loop c# =
271    case indexCharOffAddr# fo c# of
272     '\"'# ->
273        case indexCharOffAddr# fo (c# -# 1#) of
274         '\\'# ->       
275                   -- looks like an escaped something or other to me,
276                   -- better count the number of "\\"s that are immediately
277                   -- preceeding to decide if the " is escaped.
278               let
279                odd_slashes flg i# =
280                 case indexCharOffAddr# fo i# of
281                  '\\'# -> odd_slashes (not flg) (i# -# 1#)
282                  _     -> flg
283               in
284               if odd_slashes True (c# -# 2#) then
285                   -- odd number, " is ecaped.
286                   loop (c# +# 1#)
287               else  -- a real end of string delimiter after all.
288                   StringBuffer fo l# s# c#
289         _ -> StringBuffer fo l# s# c#
290     '\NUL'# ->
291         if c# >=# l# then -- hit sentinel, this doesn't look too good..
292            StringBuffer fo l# l# l#
293         else
294            loop (c# +# 1#)
295     _ -> loop (c# +# 1#)
296
297
298 untilEndOfChar# :: StringBuffer -> StringBuffer
299 untilEndOfChar# (StringBuffer fo l# s# c#) = 
300  loop c# 
301  where
302   loop c# =
303    case indexCharOffAddr# fo c# of
304     '\''# ->
305        case indexCharOffAddr# fo (c# -# 1#) of
306         '\\'# ->
307            case indexCharOffAddr# fo (c# -# 2#) of      
308              '\\'# -> -- end of char
309                    StringBuffer fo l# s# c#
310              _ -> loop (c# +# 1#) -- false alarm
311         _ -> StringBuffer fo l# s# c#
312     '\NUL'# ->
313         if c# >=# l# then -- hit sentinel, this doesn't look too good..
314            StringBuffer fo l# l# l#
315         else
316            loop (c# +# 1#)
317     _ -> loop (c# +# 1#)
318
319 untilChar# :: StringBuffer -> Char# -> StringBuffer
320 untilChar# (StringBuffer fo l# s# c#) x# = 
321  loop c# 
322  where
323   loop c# =
324    if indexCharOffAddr# fo c# `eqChar#` x# then
325       StringBuffer fo l# s# c#
326    else
327       loop (c# +# 1#)
328
329          -- conversion
330 lexemeToString :: StringBuffer -> String
331 lexemeToString (StringBuffer fo _ start_pos# current#) = 
332  if start_pos# ==# current# then
333     ""
334  else
335 #if defined(__GLASGOW_HASKELL__) && __GLASGOW_HASKELL__ <= 205
336     byteArrayToString (copySubStr (A# fo) (I# start_pos#) (I# (current# -# start_pos#)))
337 #else
338     unpackCStringBA (copySubStr (A# fo) (I# start_pos#) (I# (current# -# start_pos#)))
339 #endif
340     
341 lexemeToByteArray :: StringBuffer -> _ByteArray Int
342 lexemeToByteArray (StringBuffer fo _ start_pos# current#) = 
343  if start_pos# ==# current# then
344     error "lexemeToByteArray" 
345  else
346     copySubStr (A# fo) (I# start_pos#) (I# (current# -# start_pos#))
347
348 lexemeToFastString :: StringBuffer -> FastString
349 lexemeToFastString (StringBuffer fo l# start_pos# current#) =
350  if start_pos# ==# current# then
351     mkFastCharString2 (A# fo) (I# 0#)
352  else
353     mkFastSubString (A# fo) (I# start_pos#) (I# (current# -# start_pos#))
354
355 {-
356  Create a StringBuffer from the current lexeme, and add a sentinel
357  at the end. Know What You're Doing before taking this function
358  into use..
359 -}
360 lexemeToBuffer :: StringBuffer -> StringBuffer
361 lexemeToBuffer (StringBuffer fo l# start_pos# current#) =
362  if start_pos# ==# current# then
363     StringBuffer fo 0# start_pos# current# -- an error, really. 
364  else
365     unsafeWriteBuffer (StringBuffer fo (current# -# start_pos#) start_pos# start_pos#)
366                       (current# -# 1#)
367                       '\NUL'#
368
369 \end{code}