-
Notifications
You must be signed in to change notification settings - Fork 8
/
parser-combinator.slide
473 lines (374 loc) · 10.5 KB
/
parser-combinator.slide
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
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
# Parsec
Monadic parser combinators
24th Nov 2023
YinYin Chiu
Software Engineer, Oursky
## What is a parser?
You have something with a loose structure (mostly string)
You want to have something to convert that to a known structure.
For example, given a string `'2023-11-24'`, you want to convert it to a date representation.
```
{
year: 2023,
month: 11,
day: 24,
}
```
Note: Today we are !!Not focusing on performance!! !!Not focusing on performance!! !!Not focusing on performance!!
## Create a parser
Something to match
--> Create some steps with some rules to match
--> `Parser<Something>`
## Combine parsers
`Parser<A>` + `Parser<B>` = `Parser<C>`
Combine `Parser<A>` with `Parser<B>` (via a combinator) to produce a new parser `Parser<C>`
which can parse more complicated things
## Run a parser
- Input
- thing to parse
- `Parser<Something>`
- Output
- Success or Failure
## Consider a simple parser
Parsing character A
- Input
- some string
- Output
- remaining input
- true / false
## Parsing character A
```
const parseCharacter_a = (str: string) => {
if (str.length === 0) {
return [false, ""]
}
if (str[0] === "a") {
return [true, str.substring(1)]
}
return [false, str]
}
```
```
parseCharacter_a("abc") // [true, "bc"]
parseCharacter_a("bca") // [false, "bca"]
parseCharacter_a("") // [false, ""]
```
## Some improvement we can make
1. Change to not only parse a
2. Include the parsed value in the result
3. Maybe some error messages?
## Improvement on char parser
```
type ParseResult<T> =
| {type: "Success", value: T, remaining: string}
| {type: "Failure", errorMessage: string}
type Char = string;
const parseCharacter = (char: Char, str: string) => {
if (str.length === 0) {
return Failure("Empty string")
}
if (str[0] === char) {
return Success(value: char, remaining: str.substring(1))
}
return Failure(`Expecting ${char}, but got ${str[0]}`)
}
parseCharacter("a", "abc") // Success(value: "a", remaining: "bc")
parseCharacter("a", "bca") // Failure("Expecting a, but got b")
parseCharacter("b", "bca") // Success(value: "b", remaining: "ca")
```
## More Improvement on char parser
But often we only get the input string after something...
so we need to make the parse function run later
```
const makeParseCharacter = (char: Char) => {
const parseCharacter = (str: string) => {
if (str.length === 0) {
return Failure("Empty string")
}
if (str[0] === char) {
return Success(value: char, remaining: str.substring(1))
}
return Failure(`Expecting ${char}, but got ${str[0]}`)
}
return parseCharacter;
}
const parseCharacter_a = makeParseCharacter("a")
parseCharacter_a("abc") // Success(value: "a", remaining: "bc")
parseCharacter_a("bca") // Failure("Expecting a, but got b")
```
## Let's make a type for parser
```
type Parser<T> = (str: string) => ParseResult<T>
function Parser<T>(f: Parser<T>): Parser<T> {
return f;
}
const pCharacter = (char: Char): Parser<Char> => {
const parseCharacter = (str: string): ParseResult<Char> => {
if (str.length === 0) {
return Failure("Empty string")
}
if (str[0] === char) {
return Success(value: char, remaining: str.substring(1))
}
return Failure(`Expecting ${char}, but got ${str[0]}`)
}
return Parser(parseCharacter);
}
const pChar_a = pCharacter("a")
pChar_a("abc") // Success(value: "a", remaining: "bc")
pChar_a("bca") // Failure("Expecting a, but got b")
```
## That's it for the parser part
## Combinator
- Combinator is used to combine things to get more complex things
- e.g.
- `+`
- number + number = number
- `Array.concat`
- array concat array = array
- Parser ????(what is this) Parser = Parser
## Basic parser combinators
- Parser _andThen_ Parser => Parser
- Parser _orElse_ Parser => Parser
- Parser _map_ (transformer) => Parser
## AndThen
- Run the first parser
- If fails, return
- Then, run the second parser with the remaining input
- If fails, return
If both parsers succeed, return both result with a tuple
## AndThen
```
function andThen<A, B>(parser1: Parser<A>, parser2: Parser<B>): Parser<[A, B]> {
return Parser<[A, B]>((str) => {
const result1 = parser1(str);
if (isFailure(result1)) {
return Failure(result1.errorMessage)
}
const {value: value1, remaining: remaining1} = result1
const result2 = parser2(remaining1)
if (isFailure(result2)) {
return Failure(result2.errorMessage)
}
const {value: value2, remaining: remaining2} = result2
return Success(value: [value1, value2], remaining: remaining2)
})
}
```
## Example on AndThen
```
const parseA = pCharacter("A")
const parseB = pCharacter("B")
const parseAAndThenB = andThen(parseA, parseB)
parseAAndThenB("ABC") // Success(value: ["A", "B"], remaining: "C")
parseAAndThenB("ZBC") // Failure("Expecting A, but got Z")
parseAAndThenB("AZC") // Failure("Expecting B, but got Z")
```
## OrElse
- Run the first parser
- If success, return the result
- If fails, run the second parser with the **original input**
- Return the result from second parser
```
function orElse<A>(parser1: Parser<A>, parser2: Parser<A>): Parser<A> {
return Parser<A>((str) => {
const result1 = parser1(str);
if (isSuccess(result1)) {
return result1;
}
const result2 = parser2(str)
return result2;
})
}
```
## Example on orElse
```
const parseA = pCharacter("A")
const parseB = pCharacter("B")
const parseAOrB = orElse(parseA, parseB)
parseAOrB("AXX") // Success(value: "A", "XX")
parseAOrB("BXX") // Success(value: "B", "XX")
parseAOrB("CXX") // Failure("Expecting B, but got C")
````
## map
- Run the first parser
- If success, transform the parsed value with the transformer
- If fails, return the failure
```
function map<A, B>(fmap: ((a: A) => B), parser: Parser<A>): Parser<B> {
return Parser<B>((str) => {
const result = parser(str);
if (isSuccess(result)) {
return Success(value: fmap(result.value), remaining: result.remaining)
}
return result;
})
}
```
## Example on orElse
```
const parseA = pCharacter("A")
const parseB = pCharacter("B")
const parseAAndThenB = andThen(parseA, parseB)
const parseAAndThenBToString = map(([A, B]) => `${A}${B}`, parseAAndThenB)
parseAAndThenBToString("ABC") // Success(value: "AB", remaining: "C")
parseAAndThenBToString("ZBC") // Failure("Expecting A, but got Z")
````
## Advanced combinator
One of any chars
```
function any(chars: Char[]): Parser<Char> {
return chars.map(pCharacter).reduce(orElse)
}
```
Match String
```
function sequence<A>(parsers: Parser<A>[]): Parser<A[]> {
const concatResults = (p1: Parser<A[]>, p2: Parser<A[]>) => {
let oneAndThenTwo = andThen(p1, p2)
return map(([a,b]) => a.concat(b), oneAndThenTwo)
}
return parsers.map(p => map((a) => [a], p)).reduce(concatResults)
}
function pString(str: string): Parser<string> {
const ps = sequence(str.split("").map(pCharacter));
return map(ss => ss.join(""), ps)
}
```
## Advanced combinator (2)
andThen -> Take the first result
```
function andThenTakeFirst<A, B>(
parser1: Parser<A>,
parser2: Parser<B>
): Parser<A> {
return map(([a]: [A, B]) => a, andThen(parser1, parser2));
}
```
andThen -> Take the second result
```
function andThenTakeSecond<A, B>(
parser1: Parser<A>,
parser2: Parser<B>
): Parser<A> {
return map(([a, b]: [A, B]) => b, andThen(parser1, parser2));
}
```
## Advanced combinator (3)
between
```
function between<A, B, C>(
parser1: Parser<A>,
parser2: Parser<B>,
parser3: Parser<C>,
): Parser<B> {
return andThenTakeFirst(andThenTakeSecond(parser1, parser2), parser3);
}
```
## Example 1
We want to parse `YYYY-MM-DD` or `YYYY/MM/DD`
We can first define some primitives
```
const digit = any(["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]);
const year = map(
(s: string[]) => Number(s.join("")),
sequence([digit, digit, digit, digit]),
);
const month = map(
(s: string[]) => Number(s.join("")),
sequence([digit, digit]),
);
const day = map((s: string[]) => Number(s.join("")), sequence([digit, digit]));
const separator = orElse(pCharacter("-"), pCharacter('/'));
```
## Example 1 Cont.
```
// YYYY-MM-DD
const dateStringParser = map(
([year, month, day]) => ({
year,
month,
day,
}),
sequence([
andThenTakeFirst(year, separator),
andThenTakeFirst(month, separator),
day,
]),
);
dateStringParser('2023-11-24') // Success(value: {year: 2023, month: 11, day: 24}, remaining: "")
dateStringParser('2023/11/24') // Success(value: {year: 2023, month: 11, day: 24}, remaining: "")
```
## Example 2
We want to parse a HKID
We can add more useful combinator
```
function satisfy(predicate: ((char: Char) => boolean)): Parser<Char> {
const parse = (str: string): ParseResult<Char> => {
if (str.length === 0) {
return Failure("Empty string")
}
if (predicate(str[0])) {
return Success(str[0], str.substring(1))
}
return Failure(`${str[0]} cannot satisfy the condition`)
}
return Parser(parse);
}
```
Btw, we can replace pCharacter with
```
const pCharacter = (char: Char) => satisfy((input) => char === input);
```
## Example 2 Cont.
```
const anyLetter = satisfy((char) => /\w/.test(char))
const anyNumber = satisfy((char) => /\d/.test(char))
const parseIDNumber = sequence([
anyLetter,
anyNumber,
anyNumber,
anyNumber,
anyNumber,
anyNumber,
anyNumber,
between(pCharacter("("), anyNumber, pCharacter(")")),
]);
```
## Example 2 Cont.
```
const anyLetter = satisfy((char) => /\w/.test(char))
const anyNumber = satisfy((char) => /\d/.test(char))
const parseIDNumber = andThen(
andThen(
anyLetter,
many(anyNumber), // <-- try implement many yourself
),
between(pCharacter("("), anyNumber, pCharacter(")")),
)
```
## Compare to regex
- Regex only can give you result in string
- Cannot further process intermediate result
- Parser combinators are more understandable
- We can define some smaller problems for a big problem
- Define small parsers and combine them with combinators
- e.g. define how to parse number and then define how to parse a date string
## A journey of a thousand miles begins with a single step
Try to define your parsers
Try to define your combinators
Try to use parsec in your project
## Parsec implementation
- C#
- https://github.com/Pjanssen/ParsecSharp
- Go
- https://github.com/prataprc/goparsec
- Kotlin
- https://github.com/d-plaindoux/parsec.kotlin
- Python
- https://github.com/sighingnow/parsec.py
- Typescript
- https://github.com/microsoft/ts-parsec
- Swift
- https://github.com/davedufresne/SwiftParsec