marser 0.1.0

Parser combinator toolkit with matcher-level backtracking and rich error reporting.
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
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
use marser::capture;
use marser::{
    error::{AnnotationKind, FurthestFailError, InlineError},
    label::WithLabel,
    matcher::{
        Matcher, MatcherCombinator, commit_on,
        if_error::{if_error, if_error_else_fail},
        many, negative_lookahead,
        none_of::none_of,
        one_or_more, optional,
        parser_matcher::match_parsed,
        positive_lookahead, unwanted,
    },
    one_of::one_of,
    parser::{DeferredWeak, Parser, ParserCombinator, recursive},
};

#[derive(Clone, Debug)]
pub enum UnaryOp {
    Neg,
    Not,
}

#[derive(Clone, Debug)]
pub enum BinOp {
    Add,
    Sub,
    Mul,
    Div,
    Less,
    LessOrEqual,
    Equal,
    GreaterOrEqual,
    Greater,
    And,
    Or,
}

#[derive(Clone, Debug)]
pub enum Expr<'src> {
    Num(f64),
    Str(&'src str),
    Bool(bool),
    Var(&'src str),
    UnaryOp {
        operand: Box<Expr<'src>>,
        op: UnaryOp,
    },
    BinOp {
        lhand: Box<Expr<'src>>,
        rhand: Box<Expr<'src>>,
        op: BinOp,
    },
    FuncCall {
        name: &'src str,
        args: Vec<Expr<'src>>,
    },
    Group(Box<Expr<'src>>),
    Invalid(&'src str),
}

#[derive(Clone, Debug)]
pub struct Block<'src> {
    pub statements: Vec<Statement<'src>>,
}

#[derive(Clone, Debug)]
pub enum Statement<'src> {
    Let {
        name: &'src str,
        value: Expr<'src>,
    },
    Assign {
        name: &'src str,
        value: Expr<'src>,
    },
    If {
        condition: Expr<'src>,
        then: Block<'src>,
        else_if: Vec<(Expr<'src>, Block<'src>)>,
        else_block: Option<Block<'src>>,
    },
    While {
        condition: Expr<'src>,
        body: Block<'src>,
    },
    Return(Option<Expr<'src>>),
    Expr(Expr<'src>),
}

#[derive(Clone, Debug)]
pub struct FunctionDef<'src> {
    pub name: &'src str,
    pub params: Vec<&'src str>,
    pub body: Block<'src>,
}

fn whitespace<'src, MRes>() -> impl Matcher<'src, &'src str, MRes> {
    many(one_of((' ', '\t', '\r', '\n')))
}

fn inline_whitespace<'src, MRes>() -> impl Matcher<'src, &'src str, MRes> {
    many(one_of((' ', '\t', '\r')))
}

fn identifier<'src>() -> impl Parser<'src, &'src str, Output = &'src str> {
    capture!((
        bind_slice!(
            (
                one_of(('a'..='z', 'A'..='Z', '_')),
                many(one_of(('a'..='z', 'A'..='Z', '0'..='9', '_'))),
            ),
            slice as &'src str
        ), whitespace())
        => slice
    )
}

fn reserved_word<'src, MRes>() -> impl Matcher<'src, &'src str, MRes> {
    one_of((
        match_parsed(identifier(), "let"),
        match_parsed(identifier(), "if"),
        match_parsed(identifier(), "else"),
        match_parsed(identifier(), "while"),
        match_parsed(identifier(), "true"),
        match_parsed(identifier(), "false"),
        match_parsed(identifier(), "fn"),
        match_parsed(identifier(), "return"),
    ))
}

fn user_identifier<'src>() -> impl Parser<'src, &'src str, Output = &'src str> {
    capture!(
        (
            negative_lookahead(reserved_word()),
            bind!(identifier(), name),
        ) => name
    )
    .with_label("identifier")
}

fn number_expr<'src>() -> impl Parser<'src, &'src str, Output = Expr<'src>> {
    capture!(
        commit_on(
            positive_lookahead(one_of(('.', '0'..='9'))),
            bind_slice!((
                many('0'..='9'),
                optional((
                    '.',
                    one_or_more('0'..='9')
                ))
            ), slice as &'src str))
        => slice.parse().unwrap()
    )
    .map_output(Expr::Num)
    .add_error_info(capture!((
        many('0'..='9'),
        '.',
        negative_lookahead('0'..='9')
        )
        => Box::new(|e: &mut FurthestFailError| {
            e.add_note("Numbers must have digits after the decimal point");
        }) as Box<_>
    ))
    .recover_with(capture!(
        bind_slice!(
            many(one_of(('0'..='9', '.'))),
            slice as &'src str
        )
        => Expr::Invalid(slice)
    ))
}

fn string_expr<'src>() -> impl Parser<'src, &'src str, Output = Expr<'src>> {
    capture!(
        commit_on(
            bind_span!('"', open_quote_span as (usize, usize)),
            (
                bind_slice!(
                    many(none_of(('"', '\n'))),
                    slice as &'src str
                ),
                '"'.err_if_no_match(use_binds!(|ctx| {
                    let open_quote_span: Option<(usize, usize)> = open_quote_span.copied();
                    InlineError::new("missing closing quote")
                        .with_span(Some(ctx.span()))
                        .with_annotation(
                            open_quote_span.unwrap(),
                            "quote opened here",
                            AnnotationKind::Context,
                        )
                }))
            )
        )
        => slice
    )
    .map_output(Expr::Str)
}

fn bool_expr<'src>() -> impl Parser<'src, &'src str, Output = Expr<'src>> {
    one_of(("true".to(true), "false".to(false))).map_output(Expr::Bool)
}

fn expr<'src>() -> impl Parser<'src, &'src str, Output = Expr<'src>> {
    recursive(|expr| {
        let group = capture!(commit_on(
            bind_span!('(', open_paren_span as (usize, usize)),
            (
                whitespace(),
                bind!(expr.clone(), expr_inner),
                ')'.err_if_no_match(use_binds!(|ctx| {
                    let open_paren_span: Option<(usize, usize)> = open_paren_span.copied();
                    InlineError::new("missing closing parenthesis")
                        .with_span(Some(ctx.span()))
                        .with_annotation(
                            open_paren_span.unwrap(),
                            "parenthesis opened here",
                            AnnotationKind::Context,
                        )
                }))
            )
        ) => Expr::Group(Box::new(expr_inner)));

        let function_call = capture!(
            commit_on((
                bind!(user_identifier(), name),
                bind_span!('(', open_paren_span as (usize, usize))
            ),(
                optional((
                    bind!(expr.clone(), *args),
                    many((
                        ','.try_insert_if_missing("missing comma between arguments"),
                        inline_whitespace(),
                        if_error(many(unwanted(',', "missing argument"))),
                        inline_whitespace(),
                        bind!(expr.clone(), *args),
                    )),
                    if_error(many(unwanted(',', "trailing comma"))),
                )),
                if_error(many(unwanted(',', "missing argument"))),
                ')'.err_if_no_match(use_binds!(|ctx| {
                    let open_paren_span: Option<(usize, usize)> = open_paren_span.copied();
                    InlineError::new("missing closing parenthesis")
                        .with_span(Some(ctx.span()))
                        .with_annotation(
                            open_paren_span.unwrap(),
                            "bracket opened here",
                            AnnotationKind::Context,
                        )
                }))
            )
            ) => Expr::FuncCall { name, args }
        );

        let var_expr = user_identifier().map_output(Expr::Var);

        let invalid_expr = capture!(
            bind_slice!(
                one_or_more(none_of((
                    whitespace(), '(', ')', '"', '0'..='9', 'a'..='z', 'A'..='Z', '_', '[', ']',
                    one_of(('+', '-', '*', '/', '<', '>', '=', '!', '&', '|', ',', ';'))
                ))),
                slice as &'src str
            )
            => Expr::Invalid(slice)
        )
        .with_label("invalid expression");

        let primary = one_of((
            number_expr(),
            string_expr(),
            bool_expr(),
            function_call,
            var_expr,
            group,
            invalid_expr,
        ));

        let unary = one_of((
            capture!(
                (
                    one_or_more(bind!(one_of(('-'.to(UnaryOp::Neg), '!'.to(UnaryOp::Not))), *ops)),
                    inline_whitespace(),
                    one_of((
                        bind!(primary.clone(), operand),
                        if_error_else_fail(unwanted(
                            bind!(().to(Expr::Invalid("")), operand),
                            "missing operand after unary operator"
                        ))
                    ))
                )
                => ops.into_iter().rev().fold(operand, |acc, op| {
                    Expr::UnaryOp {
                        operand: Box::new(acc),
                        op,
                    }
                })
            ),
            primary.clone(),
        ))
        .erase_types();

        let mul_or_div = capture!(
            (
                bind!(unary.clone(), first_operand),
                whitespace(),
                many((
                    bind!(one_of(('*'.to(BinOp::Mul), '/'.to(BinOp::Div))), *ops),
                    inline_whitespace(),
                    one_of((
                        bind!(unary.clone(), *operands),
                        if_error_else_fail(unwanted(
                            bind!(().to(Expr::Invalid("")), *operands),
                            "missing operand"
                        ))
                    ))
                ))
            )
            => {
                ops.into_iter().zip(operands).fold(first_operand, |acc, (op, operand)| {
                    Expr::BinOp {
                        lhand: Box::new(acc),
                        rhand: Box::new(operand),
                        op,
                    }
                })
            }
        )
        .erase_types();

        let add_or_sub = capture!(
            (
                bind!(mul_or_div.clone(), first_operand),
                whitespace(),
                many((
                    bind!(one_of(('+'.to(BinOp::Add), '-'.to(BinOp::Sub))), *ops),
                    inline_whitespace(),
                    one_of((
                        bind!(mul_or_div.clone(), *operands),
                        if_error_else_fail(
                            unwanted(
                                bind!(().to(Expr::Invalid("")), *operands),
                                "missing operand"
                            )
                        )
                    ))
                ))
            )
            => {
                ops.into_iter().zip(operands).fold(first_operand, |acc, (op, operand)| {
                    Expr::BinOp {
                        lhand: Box::new(acc),
                        rhand: Box::new(operand),
                        op,
                    }
                })
            }
        )
        .erase_types();

        let comparison = capture!(
            (
                bind!(add_or_sub.clone(), first_operand),
                whitespace(),
                many((
                    bind!(one_of((
                        "<=".to(BinOp::LessOrEqual),
                        '<'.to(BinOp::Less),
                        "==".to(BinOp::Equal),
                        ">=".to(BinOp::GreaterOrEqual),
                        '>'.to(BinOp::Greater),
                    )), *ops),
                    inline_whitespace(),
                    one_of((
                        bind!(add_or_sub.clone(), *operands),
                        if_error_else_fail(unwanted(
                            bind!(().to(Expr::Invalid("")), *operands),
                            "missing operand"
                        ))
                    ))
                ))
            )
            => {
                ops.into_iter().zip(operands).fold(first_operand, |acc, (op, operand)| {
                    Expr::BinOp {
                        lhand: Box::new(acc),
                        rhand: Box::new(operand),
                        op,
                    }
                })
            }
        )
        .erase_types();

        let and_expr = capture!(
            (
                bind!(comparison.clone(), first_operand),
                whitespace(),
                many((
                    bind!("&&".to(BinOp::And), *ops),
                    inline_whitespace(),
                    one_of((
                        bind!(comparison.clone(), *operands),
                        if_error_else_fail(unwanted(
                            bind!(().to(Expr::Invalid("")), *operands),
                            "missing operand"
                        ))
                    ))
                ))
            )
            => {
                ops.into_iter().zip(operands).fold(first_operand, |acc, (op, operand)| {
                    Expr::BinOp {
                        lhand: Box::new(acc),
                        rhand: Box::new(operand),
                        op,
                    }
                })
            }
        )
        .erase_types();

        let or_expr = capture!(
            (
                bind!(and_expr.clone(), first_operand),
                whitespace(),
                many((
                    bind!("||".to(BinOp::Or), *ops),
                    inline_whitespace(),
                    one_of((
                        bind!(and_expr.clone(), *operands),
                        if_error_else_fail(unwanted(
                            bind!(().to(Expr::Invalid("")), *operands),
                            "missing operand"
                        ))
                    ))
                ))
            )
            => {
                ops.into_iter().zip(operands).fold(first_operand, |acc, (op, operand)| {
                    Expr::BinOp {
                        lhand: Box::new(acc),
                        rhand: Box::new(operand),
                        op,
                    }
                })
            }
        )
        .erase_types();

        one_of((
            if_error_else_fail(capture!((
                    bind!(or_expr.clone(), valid_expr),
                    many((
                        unwanted((), "missing operand"),
                        or_expr.clone().ignore_result()
                    )),
                ) => valid_expr)),
            or_expr,
        ))
    })
    .erase_types()
}

fn block<'src>() -> impl Parser<'src, &'src str, Output = Block<'src>> {
    recursive(|block: DeferredWeak<_, _>| {
        let let_stmt = capture!(
            commit_on(
                (
                    match_parsed(identifier(), "let"),
                ),
                (
                    bind!(user_identifier(), name),
                    '=',
                    whitespace(),
                    bind!(expr(), value),
                )
            ) => Statement::Let { name, value }
        )
        .add_error_info(one_of((capture!((
                match_parsed(identifier(), "let"),
                negative_lookahead(identifier().ignore_result()),
                bind_span!((), span)
            ) => Box::new(move|e: &mut FurthestFailError| {
                e.add_annotation(
                    span,
                    "missing identifier",
                    AnnotationKind::Context,
                );
            }) as Box<_>),)))
        .erase_types();

        let assign_stmt = capture!(
            (
                bind!(user_identifier(), name),
                '=',
                whitespace(),
                bind!(expr(), value),
            ) => Statement::Assign { name, value }
        )
        .erase_types();

        let if_stmt = capture!(
            commit_on(
                match_parsed(identifier(), "if"),
                (
                    bind!(expr(), condition),
                    bind!(block.clone(), then_block),
                    many((
                        match_parsed(identifier(), "else"),
                        match_parsed(identifier(), "if"),
                        bind!(expr(), *else_if_conditions),
                        bind!(block.clone(), *else_if_blocks),
                    )),
                    optional((
                        match_parsed(identifier(), "else"),
                        bind!(block.clone(), ?else_block),
                    ))
                )
            ) => Statement::If {
                condition,
                then: then_block,
                else_if: else_if_conditions.into_iter().zip(else_if_blocks).collect(),
                else_block,
            }
        )
        .erase_types();

        let while_stmt = capture!(
            commit_on(
                match_parsed(identifier(), "while"),
                (
                    bind!(expr(), condition),
                    bind!(block.clone(), body),
                )
            ) => Statement::While { condition, body }
        )
        .erase_types();

        let return_stmt = capture!(
            (
                match_parsed(identifier(), "return"),
                optional(bind!(expr(), ?value))
            ) => Statement::Return(value)
        )
        .erase_types();

        let expr_stmt = expr().map_output(Statement::Expr);

        let statements_with_semicolons = capture!(
            (
                bind!(one_of((
                    let_stmt,
                    assign_stmt,
                    return_stmt,
                    expr_stmt,
                )), stmt),
                ';'.try_insert_if_missing("missing semicolon after statement"),
                whitespace(),
            ) => stmt
        )
        .erase_types();

        let semicolon_stmt = capture!(
            (
                unwanted(';', "unexpected semicolon"),
                whitespace(),
            ) => Statement::Expr(Expr::Invalid(""))
        )
        .erase_types();

        let statement = one_of((
            if_stmt,
            while_stmt,
            semicolon_stmt,
            statements_with_semicolons,
        ))
        .erase_types();

        capture!(
            commit_on(
                bind_span!('{', open_brace_span as (usize, usize)),
                (
                    whitespace(),
                    many(bind!(statement, *statements)),
                    '}'.err_if_no_match(use_binds!(|ctx| {
                        let open_brace_span: Option<(usize, usize)> = open_brace_span.copied();
                        InlineError::new("missing closing '}'")
                            .with_span(Some(ctx.span()))
                            .with_annotation(
                                open_brace_span.unwrap(),
                                "brace opened here",
                                AnnotationKind::Context,
                            )
                    })),
                    whitespace(),
                )
            ) => Block {
                statements,
            }
        )
        .with_label("block")
        .erase_types()
    })
    .erase_types()
}

fn function_def<'src>() -> impl Parser<'src, &'src str, Output = FunctionDef<'src>> {
    capture!(
        commit_on(
            match_parsed(identifier(), "fn"),
            (
                bind!(user_identifier(), name),
                bind_span!('(', open_paren_span as (usize, usize))
                    .try_insert_if_missing("missing opening '(' in function definition"),
                optional((
                    bind!(user_identifier(), *params),
                    many((
                        ','.try_insert_if_missing("missing comma between parameters"),
                        inline_whitespace(),
                        if_error(many(unwanted(',', "missing parameter"))),
                        inline_whitespace(),
                        bind!(user_identifier(), *params),
                    )),
                    if_error(many(unwanted(',', "trailing comma"))),
                )),
                many(unwanted(',', "missing parameter")),
                ')'.err_if_no_match(use_binds!(|ctx| {
                    let open_paren_span: Option<(usize, usize)> = open_paren_span.copied();
                    InlineError::new("missing closing ')' in function definition")
                        .with_span(Some(ctx.span()))
                        .with_annotation(
                            open_paren_span.unwrap(),
                            "parenthesis opened here",
                            AnnotationKind::Context,
                        )
                })),
                whitespace(),
                bind!(block(), body),
            )
        ) => FunctionDef { name, params, body }
    )
    .with_label("function definition")
    .erase_types()
}

pub fn get_mini_language_grammar<'src>()
-> impl Parser<'src, &'src str, Output = Vec<FunctionDef<'src>>> + Clone {
    capture!(
        (
            whitespace(),
            many((
                bind!(function_def(), *functions),
                whitespace(),
            )),
        ) => functions
    )
    .with_label("file")
    .erase_types()
}