]> Git — Sourcephile - haskell/symantic.git/blob - symantic-lib/Language/Symantic/Parsing/Test.hs
Backtrack (try) the grammar only when necessary to get better error messages.
[haskell/symantic.git] / symantic-lib / Language / Symantic / Parsing / Test.hs
1 {-# LANGUAGE ConstraintKinds #-}
2 {-# OPTIONS_GHC -fno-warn-orphans #-}
3 module Parsing.Test where
4
5 import Control.Applicative (Applicative(..))
6 import qualified Control.Applicative as Alt
7 import Control.Monad
8 import qualified Data.Char as Char
9 import Data.Functor.Identity
10 import qualified Data.List as List
11 import Data.String (IsString(..))
12 import qualified Data.Text as Text
13 import Prelude hiding (any, (^), exp)
14 import qualified Text.Megaparsec as P
15
16 import Language.Symantic.Grammar
17
18 -- * Type 'ParsecT'
19 type ParsecC e s = (P.Token s ~ Char, P.Stream s, P.ErrorComponent e)
20 instance ParsecC e s => IsString (P.ParsecT e s m [Char]) where
21 fromString = P.string
22 instance ParsecC e s => Gram_Rule (P.ParsecT e s m) where
23 rule = P.label . Text.unpack
24 instance ParsecC e s => Gram_Terminal (P.ParsecT e s m) where
25 any = P.anyChar
26 eoi = P.eof
27 char = P.char
28 string = P.string
29 unicat cat = P.satisfy $ (`List.elem` cats) . Char.generalCategory
30 where cats = unicode_categories cat
31 range (l, h) = P.satisfy $ \c -> l <= c && c <= h
32 but (Terminal f) (Terminal p) = Terminal $ P.notFollowedBy (P.try p) *> f
33 instance ParsecC e s => Alter (P.ParsecT e s m) where
34 empty = Alt.empty
35 (<+>) = (Alt.<|>)
36 choice = P.choice
37 instance ParsecC e s => Try (P.ParsecT e s m) where
38 try = P.try
39 instance ParsecC e s => Gram_RegR (P.ParsecT e s m) where
40 Terminal f .*> Reg x = Reg $ f <*> x
41 instance ParsecC e s => Gram_RegL (P.ParsecT e s m) where
42 Reg f <*. Terminal x = Reg $ f <*> x
43 instance ParsecC e s => App (P.ParsecT e s m) where
44 between = P.between
45 instance ParsecC e s => Alt (P.ParsecT e s m) where
46 option = P.option
47 optional = P.optional
48 many = P.many
49 some = P.some
50 skipMany = P.skipMany
51 instance ParsecC e s => Gram_CF (P.ParsecT e s m) where
52 CF f <& Reg p = CF $ P.lookAhead f <*> p
53 Reg f &> CF p = CF $ P.lookAhead f <*> p
54 minus (CF f) (Reg p) = CF $ P.notFollowedBy (P.try p) *> f
55 instance ParsecC e s => Gram_Meta P.SourcePos (P.ParsecT e s m) where
56 metaG p = do
57 pos <- P.getPosition
58 ($ pos) <$> p
59 instance ParsecC e s => Gram_Lexer (P.ParsecT e s m)
60 instance ParsecC e s => Gram_Op (P.ParsecT e s m)
61
62 runParserT :: Monad m
63 => P.ParsecT P.Dec s m a -> s
64 -> m (Either (P.ParseError (P.Token s) P.Dec) a)
65 runParserT p = P.runParserT p ""
66
67 runParser
68 :: P.ParsecT P.Dec s Identity a -> s
69 -> Either (P.ParseError (P.Token s) P.Dec) a
70 runParser p = P.runParser p ""
71
72 elide :: String -> String
73 elide s | length s > 42 = take 42 s ++ ['…']
74 elide s = s