-
Notifications
You must be signed in to change notification settings - Fork 52
Expand file tree
/
Copy pathQuickStart.purs
More file actions
68 lines (58 loc) · 2.08 KB
/
QuickStart.purs
File metadata and controls
68 lines (58 loc) · 2.08 KB
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
module Main where
import Prelude
import Data.Foldable (fold)
import Effect (Effect)
-- https://github.com/purescript/trypurescript/blob/master/staging/src/TryPureScript.purs
import TryPureScript (h1, h3, p, text, render, code, indent, Doc)
import Parsing (Parser, runParser, ParseError(..), Position(..))
-- import Parsing.String (char, parseErrorHuman)
import Parsing.String (char)
import Control.Alt ((<|>))
import Data.Array (many)
import Data.Either (Either(..))
-- import Data.Functor (map)
ayebee :: Parser String Boolean
ayebee = do
_ <- char 'a'
b <- char 'b' <|> char 'B'
pure (b == 'B')
main :: Effect Unit
main =
render $ fold
[ h1 $ text "Examples for Parsing Quick Start"
, p $ text "Run the " <> (code $ text "ayebee") <> text " parser."
, h3 $ code (text "runParser \"aB\" ayebee")
, showResult runParser "aB" ayebee
, p $ text "Run the " <> code (text "ayebee") <> text " parser with the " <> code (text "many") <> text " combinator."
, h3 $ code (text "runParser \"aBabaB\" (many ayebee)")
, showResult runParser "aBabaB" (many ayebee)
, p $ text "Run the " <> code (text "ayebee") <> text " parser on unparsable input."
, h3 $ code (text "runParser \"aCaB\" ayebee")
, showResult runParser "aCaB" ayebee
]
showResult
:: forall a. Show a
=> (String -> Parser String a -> Either ParseError a)
-> String
-> Parser String a
-> Doc
showResult runner input parser =
let
result = runner input parser
in
case result of
Right x -> indent $ h3$ code $ text $ show x
Left err -> fold $ map (indent <<< h3 <<< code <<< text) $ parseErrorHuman input 40 err
-- for when parseErrorHuman becomes available in TryPureScript
-- https://pursuit.purescript.org/packages/purescript-parsing/10.1.0/docs/Parsing.String#v:parseErrorHuman
parseErrorHuman :: String -> Int -> ParseError -> Array String
parseErrorHuman input contextSize (ParseError msg (Position { line, column, index })) =
[ msg <> " at position index:" <> show index
<> " (line:"
<> show line
<> ", column:"
<> show column
<> ")"
, ""
, input
]