-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathParsing2.hs
76 lines (61 loc) · 2.32 KB
/
Parsing2.hs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
-- Version 1, 18 Oct 2016
-- This is just like Parsing, but re-exports the general versions of
-- operators like (<*>) and so on from the Prelude, instead of
-- Parser-specific versions.
module Parsing2
( -- * Lexing
TokenParser, makeTokenParser, emptyDef, GenLanguageDef(..)
, getIdentifier, getReserved, getReservedOp
, getNatural, getInteger, getFloat, getNaturalOrFloat
, getSymbol
, getWhiteSpace, getParens
-- * Parsing
, Parser, parse, parseFile, parseSome
, (<|>), (<$>), (<*>), (<$), (<*), (*>)
, module Text.Parsec.Expr
, module Text.Parsec.Combinator
, module Text.Parsec.Char
, try
)
where
import qualified Text.Parsec as P
import Text.Parsec.Char
import Text.Parsec.Combinator
import Text.Parsec.Expr hiding (Operator)
import Text.Parsec.Language (emptyDef)
import Text.Parsec.Pos
import Text.Parsec.Prim (Consumed (..), Reply (..), State (..),
runParsecT, try)
import Text.Parsec.String (Parser, parseFromFile)
import Text.Parsec.Token
import Control.Applicative
import Data.Functor.Identity
------------------------------------------------------------
-- Lexing
------------------------------------------------------------
getIdentifier = identifier
getReserved = reserved
getReservedOp = reservedOp
getNatural = natural
getInteger = integer
getFloat = float
getNaturalOrFloat = naturalOrFloat
getSymbol = symbol
getWhiteSpace = whiteSpace
getParens = parens
-- For more, see http://hackage.haskell.org/package/parsec-3.1.11/docs/Text-Parsec-Token.html
------------------------------------------------------------
-- Parsing
------------------------------------------------------------
parse :: Parser a -> String -> Either P.ParseError a
parse p = P.parse p ""
parseFile :: Parser a -> FilePath -> IO (Either P.ParseError a)
parseFile = parseFromFile
parseSome :: Parser a -> String -> Either P.ParseError (a, String)
parseSome p s =
case runIdentity . getReply . runIdentity $ runParsecT p (State s (initialPos "") ()) of
Ok a (State rest _ _) _ -> Right (a, rest)
Error err -> Left err
where
getReply (Consumed r) = r
getReply (Empty r) = r