8aefad5f2eb1aaae32bced502c09f09aeba66bfa
[ghc-base.git] / GHC / Unicode.hs
1 {-# OPTIONS -fno-implicit-prelude #-}
2 {-# OPTIONS -#include "WCsubst.h" #-}
3 -----------------------------------------------------------------------------
4 -- |
5 -- Module      :  GHC.Unicde
6 -- Copyright   :  (c) The University of Glasgow, 2003
7 -- License     :  see libraries/base/LICENSE
8 -- 
9 -- Maintainer  :  cvs-ghc@haskell.org
10 -- Stability   :  internal
11 -- Portability :  non-portable (GHC extensions)
12 --
13 -- Implementations for the character predicates (isLower, isUpper, etc.)
14 -- and the conversions (toUpper, toLower).  The implementation uses
15 -- libunicode on Unix systems if that is available.
16 --
17 -----------------------------------------------------------------------------
18
19 module GHC.Unicode (
20     GeneralCategory (..),
21     generalCategory,
22     isAscii, isLatin1, isControl,
23     isAsciiUpper, isAsciiLower,
24     isPrint, isSpace,  isUpper,
25     isLower, isAlpha,  isDigit,
26     isOctDigit, isHexDigit, isAlphaNum,
27     toUpper, toLower, toTitle,
28     isLetter,               -- :: Char -> Bool
29     isMark,                 -- :: Char -> Bool
30     isNumber,               -- :: Char -> Bool
31     isPunctuation,          -- :: Char -> Bool
32     isSymbol,               -- :: Char -> Bool
33     isSeparator,            -- :: Char -> Bool
34   ) where
35
36 import GHC.Base
37 import GHC.Real  (fromIntegral)
38 import GHC.Int
39 import GHC.Word
40 import GHC.Num   (fromInteger)
41 import GHC.Read
42 import GHC.Show
43 import GHC.Enum
44
45 #include "HsBaseConfig.h"
46
47 -- | Unicode General Categories (column 2 of the UnicodeData table)
48 -- in the order they are listed in the Unicode standard.
49
50 data GeneralCategory
51         = UppercaseLetter       -- Lu  Letter, Uppercase
52         | LowercaseLetter       -- Ll  Letter, Lowercase
53         | TitlecaseLetter       -- Lt  Letter, Titlecase
54         | ModifierLetter        -- Lm  Letter, Modifier
55         | OtherLetter           -- Lo  Letter, Other
56         | NonSpacingMark        -- Mn  Mark, Non-Spacing
57         | SpacingCombiningMark  -- Mc  Mark, Spacing Combining
58         | EnclosingMark         -- Me  Mark, Enclosing
59         | DecimalNumber         -- Nd  Number, Decimal
60         | LetterNumber          -- Nl  Number, Letter
61         | OtherNumber           -- No  Number, Other
62         | ConnectorPunctuation  -- Pc  Punctuation, Connector
63         | DashPunctuation       -- Pd  Punctuation, Dash
64         | OpenPunctuation       -- Ps  Punctuation, Open
65         | ClosePunctuation      -- Pe  Punctuation, Close
66         | InitialQuote          -- Pi  Punctuation, Initial quote
67         | FinalQuote            -- Pf  Punctuation, Final quote
68         | OtherPunctuation      -- Po  Punctuation, Other
69         | MathSymbol            -- Sm  Symbol, Math
70         | CurrencySymbol        -- Sc  Symbol, Currency
71         | ModifierSymbol        -- Sk  Symbol, Modifier
72         | OtherSymbol           -- So  Symbol, Other
73         | Space                 -- Zs  Separator, Space
74         | LineSeparator         -- Zl  Separator, Line
75         | ParagraphSeparator    -- Zp  Separator, Paragraph
76         | Control               -- Cc  Other, Control
77         | Format                -- Cf  Other, Format
78         | Surrogate             -- Cs  Other, Surrogate
79         | PrivateUse            -- Co  Other, Private Use
80         | NotAssigned           -- Cn  Other, Not Assigned
81         deriving (Eq, Ord, Enum, Read, Show, Bounded)
82
83 -- | Retrieves the general Unicode category of the character.
84 generalCategory :: Char -> GeneralCategory
85 generalCategory c = toEnum (wgencat (fromIntegral (ord c)))
86
87 -- ------------------------------------------------------------------------
88 -- These are copied from Hugs Unicode.hs
89
90 -- derived character classifiers
91
92 isLetter :: Char -> Bool
93 isLetter c = case generalCategory c of
94         UppercaseLetter         -> True
95         LowercaseLetter         -> True
96         TitlecaseLetter         -> True
97         ModifierLetter          -> True
98         OtherLetter             -> True
99         _                       -> False
100
101 isMark :: Char -> Bool
102 isMark c = case generalCategory c of
103         NonSpacingMark          -> True
104         SpacingCombiningMark    -> True
105         EnclosingMark           -> True
106         _                       -> False
107
108 isNumber :: Char -> Bool
109 isNumber c = case generalCategory c of
110         DecimalNumber           -> True
111         LetterNumber            -> True
112         OtherNumber             -> True
113         _                       -> False
114
115 isPunctuation :: Char -> Bool
116 isPunctuation c = case generalCategory c of
117         ConnectorPunctuation    -> True
118         DashPunctuation         -> True
119         OpenPunctuation         -> True
120         ClosePunctuation        -> True
121         InitialQuote            -> True
122         FinalQuote              -> True
123         OtherPunctuation        -> True
124         _                       -> False
125
126 isSymbol :: Char -> Bool
127 isSymbol c = case generalCategory c of
128         MathSymbol              -> True
129         CurrencySymbol          -> True
130         ModifierSymbol          -> True
131         OtherSymbol             -> True
132         _                       -> False
133
134 isSeparator :: Char -> Bool
135 isSeparator c = case generalCategory c of
136         Space                   -> True
137         LineSeparator           -> True
138         ParagraphSeparator      -> True
139         _                       -> False
140
141 -- | Selects the first 128 characters of the Unicode character set,
142 -- corresponding to the ASCII character set.
143 isAscii                 :: Char -> Bool
144 isAscii c               =  c <  '\x80'
145
146 -- | Selects the first 256 characters of the Unicode character set,
147 -- corresponding to the ISO 8859-1 (Latin-1) character set.
148 isLatin1                :: Char -> Bool
149 isLatin1 c              =  c <= '\xff'
150
151 isAsciiUpper, isAsciiLower :: Char -> Bool
152 isAsciiLower c          =  c >= 'a' && c <= 'z'
153 isAsciiUpper c          =  c >= 'A' && c <= 'Z'
154
155 -- | Selects control characters, which are the non-printing characters of
156 -- the Latin-1 subset of Unicode.
157 isControl               :: Char -> Bool
158
159 -- | Selects printable Unicode characters
160 -- (letters, numbers, marks, punctuation, symbols and spaces).
161 isPrint                 :: Char -> Bool
162
163 -- | Selects white-space characters in the Latin-1 range.
164 -- (In Unicode terms, this includes spaces and some control characters.)
165 isSpace                 :: Char -> Bool
166 -- isSpace includes non-breaking space
167 -- Done with explicit equalities both for efficiency, and to avoid a tiresome
168 -- recursion with GHC.List elem
169 isSpace c               =  c == ' '     ||
170                            c == '\t'    ||
171                            c == '\n'    ||
172                            c == '\r'    ||
173                            c == '\f'    ||
174                            c == '\v'    ||
175                            c == '\xa0'  ||
176                            iswspace (fromIntegral (ord c)) /= 0
177
178 -- | Selects alphabetic Unicode characters (letters) that are not lower-case.
179 -- (In Unicode terms, this includes letters in upper and title cases,
180 -- as well as modifier letters and other letters.)
181 isUpper                 :: Char -> Bool
182
183 -- | Selects lower-case alphabetic Unicode characters (letters).
184 isLower                 :: Char -> Bool
185
186 -- | Selects alphabetic Unicode characters (letters).
187 isAlpha                 :: Char -> Bool
188
189 -- | Selects alphabetic or numeric digit Unicode characters.
190 --
191 -- Note that numeric digits outside the ASCII range are selected by this
192 -- function but not by 'isDigit'.  Such digits may be part of identifiers
193 -- but are not used by the printer and reader to represent numbers.
194 isAlphaNum              :: Char -> Bool
195
196 -- | Selects ASCII digits, i.e. @\'0\'@..@\'9\'@.
197 isDigit                 :: Char -> Bool
198
199 -- | Selects ASCII octal digits, i.e. @\'0\'@..@\'7\'@.
200 isOctDigit              :: Char -> Bool
201 isOctDigit c            =  c >= '0' && c <= '7'
202
203 -- | Selects ASCII hexadecimal digits,
204 -- i.e. @\'0\'@..@\'9\'@, @\'a\'@..@\'f\'@, @\'A\'@..@\'F\'@.
205 isHexDigit              :: Char -> Bool
206 isHexDigit c            =  isDigit c || c >= 'A' && c <= 'F' ||
207                                         c >= 'a' && c <= 'f'
208
209 -- | Convert a letter to the corresponding upper-case letter, leaving any
210 -- other character unchanged.  Any Unicode letter which has an upper-case
211 -- equivalent is transformed.
212 toUpper                 :: Char -> Char
213
214 -- | Convert a letter to the corresponding lower-case letter, leaving any
215 -- other character unchanged.  Any Unicode letter which has a lower-case
216 -- equivalent is transformed.
217 toLower                 :: Char -> Char
218
219 -- -----------------------------------------------------------------------------
220 -- Implementation with the supplied auto-generated Unicode character properties
221 -- table (default)
222
223 #if 1
224
225 -- Regardless of the O/S and Library, use the functions contained in WCsubst.c
226
227 type WInt = HTYPE_WINT_T
228
229 isDigit    c = iswdigit (fromIntegral (ord c)) /= 0
230 isAlpha    c = iswalpha (fromIntegral (ord c)) /= 0
231 isAlphaNum c = iswalnum (fromIntegral (ord c)) /= 0
232 --isSpace    c = iswspace (fromIntegral (ord c)) /= 0
233 isControl  c = iswcntrl (fromIntegral (ord c)) /= 0
234 isPrint    c = iswprint (fromIntegral (ord c)) /= 0
235 isUpper    c = iswupper (fromIntegral (ord c)) /= 0
236 isLower    c = iswlower (fromIntegral (ord c)) /= 0
237
238 toLower c = chr (fromIntegral (towlower (fromIntegral (ord c))))
239 toUpper c = chr (fromIntegral (towupper (fromIntegral (ord c))))
240 toTitle c = chr (fromIntegral (towtitle (fromIntegral (ord c))))
241
242 foreign import ccall unsafe "u_iswdigit"
243   iswdigit :: CInt -> CInt
244
245 foreign import ccall unsafe "u_iswalpha"
246   iswalpha :: CInt -> CInt
247
248 foreign import ccall unsafe "u_iswalnum"
249   iswalnum :: CInt -> CInt
250
251 foreign import ccall unsafe "u_iswcntrl"
252   iswcntrl :: CInt -> CInt
253
254 foreign import ccall unsafe "u_iswspace"
255   iswspace :: CInt -> CInt
256
257 foreign import ccall unsafe "u_iswprint"
258   iswprint :: CInt -> CInt
259
260 foreign import ccall unsafe "u_iswlower"
261   iswlower :: CInt -> CInt
262
263 foreign import ccall unsafe "u_iswupper"
264   iswupper :: CInt -> CInt
265
266 foreign import ccall unsafe "u_towlower"
267   towlower :: CInt -> CInt
268
269 foreign import ccall unsafe "u_towupper"
270   towupper :: CInt -> CInt
271
272 foreign import ccall unsafe "u_towtitle"
273   towtitle :: CInt -> CInt
274
275 foreign import ccall unsafe "u_gencat"
276   wgencat :: CInt -> Int
277
278 -- -----------------------------------------------------------------------------
279 -- No libunicode, so fall back to the ASCII-only implementation (never used, indeed)
280
281 #else
282
283 isControl c             =  c < ' ' || c >= '\DEL' && c <= '\x9f'
284 isPrint c               =  not (isControl c)
285
286 -- The upper case ISO characters have the multiplication sign dumped
287 -- randomly in the middle of the range.  Go figure.
288 isUpper c               =  c >= 'A' && c <= 'Z' || 
289                            c >= '\xC0' && c <= '\xD6' ||
290                            c >= '\xD8' && c <= '\xDE'
291 -- The lower case ISO characters have the division sign dumped
292 -- randomly in the middle of the range.  Go figure.
293 isLower c               =  c >= 'a' && c <= 'z' ||
294                            c >= '\xDF' && c <= '\xF6' ||
295                            c >= '\xF8' && c <= '\xFF'
296
297 isAlpha c               =  isLower c || isUpper c
298 isDigit c               =  c >= '0' && c <= '9'
299 isAlphaNum c            =  isAlpha c || isDigit c
300
301 -- Case-changing operations
302
303 toUpper c@(C# c#)
304   | isAsciiLower c    = C# (chr# (ord# c# -# 32#))
305   | isAscii c         = c
306     -- fall-through to the slower stuff.
307   | isLower c   && c /= '\xDF' && c /= '\xFF'
308   = unsafeChr (ord c `minusInt` ord 'a' `plusInt` ord 'A')
309   | otherwise
310   = c
311
312
313 toLower c@(C# c#)
314   | isAsciiUpper c = C# (chr# (ord# c# +# 32#))
315   | isAscii c      = c
316   | isUpper c      = unsafeChr (ord c `minusInt` ord 'A' `plusInt` ord 'a')
317   | otherwise      =  c
318
319 #endif
320