-
Notifications
You must be signed in to change notification settings - Fork 35
/
GettingStarted.lhs
439 lines (318 loc) · 11.8 KB
/
GettingStarted.lhs
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
[[getting-started]]
= Getting started
This is an introduction to parsing with Haskell and Parsec.
Prerequisites: you should know some basic Haskell and have GHC and
cabal-install installed (installing the Haskell Platform will give you
this).
This tutorial was originally written using GHC 7.6.3 and Parsec 3.1.3,
which are the versions which come with the Haskell Platform
2013.2.0.0. It should also work fine with GHC 7.8.4 and GHC 7.10.2 and
through to at least the latest release of Parsec 3.1.x.
This tutorial was written using Literate Haskell files available here:
link:https://github.com/JakeWheat/intro_to_parsing[].
I recommend you download them all, and follow along in your favourite
editor, and use GHCi to experiment. To download the intro_to_parsing
files, use:
```
git clone https://github.com/JakeWheat/intro_to_parsing.git
```
Here are the imports.
> import Text.Parsec.String (Parser)
> import Text.Parsec.String.Char (anyChar)
> import Text.Parsec.String.Char
> import FunctionsAndTypesForParsing (regularParse, parseWithEof, parseWithLeftOver)
> import Data.Char
> import Text.Parsec.String.Combinator (many1)
== First parser
The first parser:
```
anyChar :: Parser Char
```
This parser is in the module `Text.Parsec.Char`. There is a wrapper in
this tutorial's project, `Text.Parsec.String.Char`, which gives this
function a simplified type.
Whenever we write a parser which parses to a value of type `a`, we give
it the return type of `Parser a`. In this case, we parse a character
so the return type is `Parser Char`. The `Parser` type itself is in
the module `Text.Parsec.String`. We will cover this in more detail
later.
Let's use this parser. I will assume you have GHC and cabal-install
installed (which provides the 'cabal' executable) and both are in your
PATH. The Haskell Platform is one way that provides this.
Change to the directory where you downloaded the intro_to_parsing
source files (which will contain the GettingStarted.lhs file). Then
you can set up a cabal sandbox and be ready to work with the code by
running the following commands in that directory:
```
cabal v1-update
cabal v1-sandbox init
cabal v1-install parsec HUnit
cabal v1-repl
```
Now you will get the ghci prompt. Type in ':l GettingStarted.lhs'. You
can run the parser using a wrapper, enter the following at the ghci
prompt: `regularParse anyChar "a"`.
Here is a transcript of running ghci via 'cabal repl':
```
$ cabal repl
Warning: The repl command is a part of the legacy v1 style of cabal usage.
Please switch to using either the new project style and the new-repl command
or the legacy v1-repl alias as new-style projects will become the default in
the next version of cabal-install. Please file a bug if you cannot replicate a
working v1- use case with the new-style commands.
For more information, see: https://wiki.haskell.org/Cabal/NewBuild
GHCi, version 8.6.5: http://www.haskell.org/ghc/ :? for help
Prelude> :l GettingStarted.lhs
[1 of 5] Compiling Text.Parsec.String.Char ( Text/Parsec/String/Char.hs, interpreted )
[2 of 5] Compiling Text.Parsec.String.Combinator ( Text/Parsec/String/Combinator.hs, interpreted )
[3 of 5] Compiling Text.Parsec.String.Parsec ( Text/Parsec/String/Parsec.hs, interpreted )
[4 of 5] Compiling FunctionsAndTypesForParsing ( FunctionsAndTypesForParsing.lhs, interpreted )
[5 of 5] Compiling Main ( GettingStarted.lhs, interpreted )
Ok, five modules loaded.
*Main> regularParse anyChar "a"
Right 'a'
*Main>
```
You can exit ghci by entering ':quit' or using Ctrl-d. From now on, to
start ghci again, you can just change to the directory with
GettingStarted.lhs and run 'cabal repl'. ghci should have readline
support so you can browse through your command history using up and
down arrow, etc.
This is the type of `regularParse`. It is wrapper which takes a parser
function such as anyChar, and wraps it so you can parse a string to
either a parse error, or the return value from your parser function:
```
regularParse :: Parser a -> String -> Either ParseError a
```
Here are some examples of running this parser on various input:
```
*Main> regularParse anyChar "a"
Right 'a'
*Main> regularParse anyChar "b"
Right 'b'
*Main> regularParse anyChar "0"
Right '0'
*Main> regularParse anyChar " "
Right ' '
*Main> regularParse anyChar "\n"
Right '\n'
*Main> regularParse anyChar "aa"
Right 'a'
*Main> regularParse anyChar ""
Left (line 1, column 1):
unexpected end of input
*Main> regularParse anyChar " a"
Right ' '
```
You can see that if there are no characters, we get an error.
Otherwise, it takes the first character and returns it, and throws
away any trailing characters. The details of the helper function
`regularParse` will come later.
Here are two alternatives to `regularParse` you can also use for
experimenting for the time being:
```
parseWithEof :: Parser a -> String -> Either ParseError a
```
```
parseWithLeftOver :: Parser a -> String -> Either ParseError (a,String)
```
These can be useful when you are not sure if your parser is consuming
all your input string or not. The eof parser will error if you haven't
consumed all the input, and the leftover parser can instead tell you
what was not consumed from the input.
```
*Main> regularParse anyChar "a"
Right 'a'
*Main> parseWithEof anyChar "a"
Right 'a'
*Main> parseWithLeftOver anyChar "a"
Right ('a',"")
*Main> *Main> regularParse anyChar ""
Left (line 1, column 1):
unexpected end of input
*Main> parseWithEof anyChar ""
Left (line 1, column 1):
unexpected end of input
*Main> parseWithLeftOver anyChar ""
Left (line 1, column 1):
unexpected end of input
*Main> regularParse anyChar "aa"
Right 'a'
*Main> parseWithEof anyChar "aa"
Left (line 1, column 2):
unexpected 'a'
expecting end of input
*Main> parseWithLeftOver anyChar "aa"
Right ('a',"a")
*Main> parseWithLeftOver anyChar "abc"
Right ('a',"bc")
```
You can use these functions and ghci to experiment. Try running all
the parsers in ghci on various input strings as you work through the
document to get a good feel for all the different features. Tip: you
can also write the parsers inline in the function call, for example:
```
*Main> regularParse (many1 digit) "1"
Right "1"
*Main> regularParse (many1 digit) "122"
Right "122"
```
This can be used to quickly try out new ad hoc parsing code.
== Type signatures
The real Parsec functions have quite complex type signatures. This
makes a lot of things very tricky before you understand them, and can
make some of the error messages you'll see really difficult to
understand. I've created some wrapper modules, which set the types of
all the functions from Parsec we use to be much more restricted. This
will make the types easy to understand, and reduce the amount of
tricky to understand compiler errors you get. You can use this
approach when writing your own parser code with Parsec. These wrapper
modules are created with the following name pattern:
`Text.Parsec.Char` -> `Text.Parsec.String.Char`.
Later on, we will look at the general types in more detail.
== Text.Parsec.Char
Let's go through some of the functions in `Text.Parsec.Char` module from
the Parsec package. The haddock is available here:
<http://hackage.haskell.org/package/parsec-3.1.3/docs/Text-Parsec-Char.html>.
Here is the `satisfy` function, with its full type signature.
```
satisfy :: Stream s m Char => (Char -> Bool) -> ParsecT s u m Char
```
This is one of the main primitive functions in Parsec. This looks at
the next character from the current input, and if the function (`Char
-> Bool`) returns true for this character, it 'pops' it from the input
and returns it. In this way, the current position in the input string
is tracked behind the scenes.
In the simplified type wrappers, the `satisfy` function's type is this:
```
satisfy :: (Char -> Bool) -> Parser Char
```
This makes it a bit clearer what it is doing. All the functions in
`Text.Parsec.Char` are reproduced in the local `Text.Parsec.String.Char`
module with simplified types
(<https://github.com/JakeWheat/intro_to_parsing/blob/master/Text/Parsec/String/Char.hs>).
Here are some examples of satisfy in action.
```
*Main> parseWithEof (satisfy (=='a')) "a"
Right 'a'
*Main> parseWithEof (satisfy (=='b')) "a"
Left (line 1, column 1):
unexpected "a"
*Main> parseWithEof (satisfy (`elem` "abc")) "a"
Right 'a'
*Main> parseWithEof (satisfy (`elem` "abc")) "d"
Left (line 1, column 1):
unexpected "d"
*Main> parseWithEof (satisfy isDigit) "d"
Left (line 1, column 1):
unexpected "d"
*Main> parseWithEof (satisfy isDigit) "1"
Right '1'
```
You can see that it is easy to use `==`, or `elem` or one of the
functions from the Data.Char module.
If you look at the docs on hackage
<http://hackage.haskell.org/package/parsec-3.1.3/docs/Text-Parsec-Char.html>,
you can view the source. The implementations of most of the functions
in `Text.Parsec.Char` are straightforward. I recommend you look at the
source for all of these functions.
You can see in the source that the `satisfy` function is a little more
primitive than the other functions.
Here is the parser we used above in the `anyChar` parser:
```
anyChar :: Parser Char
```
If you look at the source via the haddock link above, you can see it
uses `satisfy`.
Here are some other simple wrappers of `satisfy` from
`Text.Parsec.Char` which use different validation functions.
The `char` parser parses a specific character which you supply:
```
char :: Char -> Parser Char
```
```
*Main> regularParse (char 'a') "a"
Right 'a'
*Main> regularParse (char 'a') "b"
Left (line 1, column 1):
unexpected "b"
expecting "a"
```
These parsers all parse single hardcoded characters
```
space :: Parser Char
newline :: Parser Char
tab :: Parser Char
```
They all return a `Char`. You might be able to guess what `Char` each
of them returns, you can double check your intuition using ghci.
These parser all parse one character from a hardcoded set of
characters:
```
upper :: Parser Char
lower :: Parser Char
alphaNum :: Parser Char
letter :: Parser Char
digit :: Parser Char
hexDigit :: Parser Char
octDigit :: Parser Char
```
In these cases, the return value is less redundant.
`oneOf` and `noneOf` parse any of the characters in the given list
```
oneOf :: [Char] -> Parser Char
noneOf :: [Char] -> Parser Char
```
These are just simple wrappers of satisfy using `elem`.
You should try all these parsers out in ghci, e.g.:
```
regularParse space " "
regularParse upper "A"
regularParse (char 'b') "B"
regularParse (oneOf "abc") "c"
```
Here are the final functions in `Text.Parsec.Char`:
`string` matches a complete string, one character at a time. I think
the implementation of this function is like it is for efficiency when
parsing from, e.g., `Data.Text.Text`, instead of `String`, but I'm not
sure. We will skip the detailed explanation of the implementation for
now.
```
string :: String -> Parser String
```
```
*Main> regularParse (string "one") "one"
Right "one"
*Main> regularParse (string "one") "two"
Left (line 1, column 1):
unexpected "t"
expecting "one"
```
Here is the `spaces` parser, which, if you look at the source, you can
see uses a combinator (`skipMany`). We will cover this combinator
shortly.
```
spaces :: Parser ()
```
```
*Main> regularParse spaces ""
Right ()
*Main> regularParse spaces " "
Right ()
*Main> regularParse spaces " "
Right ()
*Main> regularParse spaces " a "
Right ()
*Main> regularParse spaces "a a "
Right ()
```
It always succeeds.
== A couple of helper executables
Here are two exes which you can use to parse either a string or a file
to help you experiment. This will save you having to figure out how to
write this boilerplate until later.
<https://github.com/JakeWheat/intro_to_parsing/blob/master/ParseFile.lhs>
<https://github.com/JakeWheat/intro_to_parsing/blob/master/ParseString.lhs>
Now you can easily experiment using ghci, or with a string on the
command line, or by putting the text to parse into a file and parsing
that.