1 {-# OPTIONS -fno-implicit-prelude #-}
2 -----------------------------------------------------------------------------
3 -- |
5 -- Copyright : (c) The University of Glasgow 2002
7 --
9 -- Stability : provisional
10 -- Portability : portable
11 --
12 -- This library defines parser combinators for precedence parsing.
14 -----------------------------------------------------------------------------
17 (
20 -- * Precedences
21 Prec, -- :: *; = Int
22 minPrec, -- :: Prec; = 0
24 -- * Precedence operations
30 -- * Other operations
31 -- All are based directly on their similarly-naned 'ReadP' counterparts.
32 get, -- :: ReadPrec Char
33 look, -- :: ReadPrec String
35 pfail, -- :: ReadPrec a
38 -- * Converters
43 )
44 where
51 )
54 ( get
55 , look
56 , (+++)
57 , pfail
58 , choice
59 )
62 import GHC.Num( Num(..) )
63 import GHC.Base
65 -- ---------------------------------------------------------------------------
68 newtype ReadPrec a = P { unP :: Prec -> ReadP a }
73 fmap h (P f) = P (\n -> fmap h (f n))
76 return x = P (\_ -> return x)
77 fail s = P (\_ -> fail s)
78 P f >>= k = P (\n -> do a <- f n; let P f' = k a in f' n)
81 mzero = pfail
82 mplus = (+++)
84 -- precedences
86 type Prec = Int
88 minPrec :: Prec
89 minPrec = 0
91 -- ---------------------------------------------------------------------------
96 lift m = P (\_ -> m)
99 -- ^ Increases the precedence context by one
100 step (P f) = P (\n -> f (n+1))
103 -- ^ Resets the precedence context to zero
104 reset (P f) = P (\n -> f minPrec)
107 -- ^ @(prec n p)@ checks that the precedence context is
108 -- less than or equal to n,
109 -- * if not, fails
110 -- * if so, parses p in context n
111 prec n (P f) = P (\c -> if c <= n then f n else ReadP.pfail)
113 -- ---------------------------------------------------------------------------
114 -- Derived operations
123 P f1 +++ P f2 = P (\n -> f1 n ReadP.+++ f2 n)
129 choice ps = foldr (+++) pfail ps
131 -- ---------------------------------------------------------------------------