[project @ 2002-07-04 10:42:32 by simonmar]
[haskell-directory.git] / Text / ParserCombinators / Parsec / Char.hs
1 -----------------------------------------------------------------------------
2 -- |
3 -- Module      :  Text.ParserCombinators.Parsec.Char
4 -- Copyright   :  (c) Daan Leijen 1999-2001
5 -- License     :  BSD-style (see the file libraries/base/LICENSE)
6 -- 
7 -- Maintainer  :  daan@cs.uu.nl
8 -- Stability   :  provisional
9 -- Portability :  portable
10 --
11 -- Commonly used character parsers.
12 -- 
13 -----------------------------------------------------------------------------
14
15 module Text.ParserCombinators.Parsec.Char
16                   ( CharParser
17                   , spaces, space
18                   , newline, tab
19                   , upper, lower, alphaNum, letter
20                   , digit, hexDigit, octDigit
21                   , char, string
22                   , anyChar, oneOf, noneOf
23                   , satisfy
24                   ) where
25
26 import Prelude
27 import Data.Char
28 import Text.ParserCombinators.Parsec.Pos( updatePosChar, updatePosString )
29 import Text.ParserCombinators.Parsec.Prim
30
31 -----------------------------------------------------------
32 -- Type of character parsers
33 -----------------------------------------------------------
34 type CharParser st a    = GenParser Char st a
35
36 -----------------------------------------------------------
37 -- Character parsers
38 -----------------------------------------------------------
39 oneOf cs            = satisfy (\c -> elem c cs)
40 noneOf cs           = satisfy (\c -> not (elem c cs))
41
42 spaces              = skipMany space        <?> "white space"          
43 space               = satisfy (isSpace)     <?> "space"
44
45 newline             = char '\n'             <?> "new-line"
46 tab                 = char '\t'             <?> "tab"
47
48 upper               = satisfy (isUpper)     <?> "uppercase letter"
49 lower               = satisfy (isLower)     <?> "lowercase letter"
50 alphaNum            = satisfy (isAlphaNum)  <?> "letter or digit"
51 letter              = satisfy (isAlpha)     <?> "letter"
52 digit               = satisfy (isDigit)     <?> "digit"
53 hexDigit            = satisfy (isHexDigit)  <?> "hexadecimal digit"
54 octDigit            = satisfy (isOctDigit)  <?> "octal digit"
55
56 char c              = satisfy (==c)  <?> show [c]
57 anyChar             = satisfy (const True)
58
59 -----------------------------------------------------------
60 -- Primitive character parsers
61 -----------------------------------------------------------
62 satisfy :: (Char -> Bool) -> CharParser st Char
63 satisfy f           = tokenPrim (\c -> show [c]) 
64                                 (\pos c cs -> updatePosChar pos c) 
65                                 (\c -> if f c then Just c else Nothing)
66
67 string :: String -> CharParser st String
68 string s            = tokens show updatePosString s