summaryrefslogtreecommitdiff
path: root/dhall/src/parser.rs
blob: 022c964a46004c8d1e4d86a2465d6d01b2104623 (plain)
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
use lalrpop_util;
use itertools::*;
use pest::Parser;
use pest::iterators::Pair;

use dhall_parser::{DhallParser, Rule};

use crate::grammar;
use crate::grammar_util::{BoxExpr, ParsedExpr};
use crate::lexer::{Lexer, LexicalError, Tok};
use crate::core::{bx, Expr, Builtin, V};

pub fn parse_expr_lalrpop(s: &str) -> Result<BoxExpr, lalrpop_util::ParseError<usize, Tok, LexicalError>>  {
    grammar::ExprParser::new().parse(Lexer::new(s))
}

pub type ParseError = pest::error::Error<Rule>;

pub type ParseResult<T> = Result<T, ParseError>;

pub fn custom_parse_error(pair: &Pair<Rule>, msg: String) -> ParseError {
    let e = pest::error::ErrorVariant::CustomError{ message: msg };
    pest::error::Error::new_from_span(e, pair.as_span())
}


macro_rules! parse_aux {
    ($inner:expr, true, $x:ident : $ty:ident $($rest:tt)*) => {
        let $x = concat_idents!(parse_, $ty)($inner.next().unwrap())?;
        parse_aux!($inner, true $($rest)*)
    };
    ($inner:expr, true, $x:ident? : $ty:ident $($rest:tt)*) => {
        let $x = $inner.next().map(concat_idents!(parse_, $ty)).transpose()?;
        parse_aux!($inner, true $($rest)*)
    };
    ($inner:expr, true, $x:ident* : $ty:ident $($rest:tt)*) => {
        #[allow(unused_mut)]
        let mut $x = $inner.map(concat_idents!(parse_, $ty));
        parse_aux!($inner, false $($rest)*)
    };
    ($inner:expr, false) => {};
    ($inner:expr, true) => {
        $inner.next().ok_or(()).expect_err("Some parsed values remain unused")
    };
}

macro_rules! parse {
    ($pair:expr; ($($args:tt)*) => $body:expr) => {
        {
            #[allow(unused_mut)]
            let mut inner = $pair.into_inner();
            parse_aux!(inner, true, $($args)*);
            Ok($body)
        }
    };
}


fn parse_binop<'a, F>(pair: Pair<'a, Rule>, mut f: F) -> ParseResult<BoxExpr<'a>>
where F: FnMut(BoxExpr<'a>, BoxExpr<'a>) -> ParsedExpr<'a> {
    parse!(pair; (first: expression, rest*: expression) => {
        rest.fold_results(first, |acc, e| bx(f(acc, e)))?
    })
}

fn skip_expr(pair: Pair<Rule>) -> ParseResult<BoxExpr> {
    parse!(pair; (expr: expression) => {
        expr
    })
}

fn parse_str(pair: Pair<Rule>) -> ParseResult<&str> {
    Ok(pair.as_str().trim())
}

fn parse_natural(pair: Pair<Rule>) -> ParseResult<usize> {
    parse_str(pair.clone())?
        .parse()
        .map_err(|e: std::num::ParseIntError| custom_parse_error(&pair, format!("{}", e)))
}

fn parse_expression(pair: Pair<Rule>) -> ParseResult<BoxExpr> {
    match pair.as_rule() {
        Rule::natural_literal_raw => Ok(bx(Expr::NaturalLit(parse_natural(pair)?))),

        Rule::annotated_expression => { parse_binop(pair, Expr::Annot) }
        Rule::import_alt_expression => { skip_expr(pair) }
        Rule::or_expression => { parse_binop(pair, Expr::BoolOr) }
        Rule::plus_expression => { parse_binop(pair, Expr::NaturalPlus) }
        Rule::text_append_expression => { parse_binop(pair, Expr::TextAppend) }
        Rule::list_append_expression => { skip_expr(pair) }
        Rule::and_expression => { parse_binop(pair, Expr::BoolAnd) }
        Rule::combine_expression => { skip_expr(pair) }
        Rule::prefer_expression => { skip_expr(pair) }
        Rule::combine_types_expression => { skip_expr(pair) }
        Rule::times_expression => { parse_binop(pair, Expr::NaturalTimes) }
        Rule::equal_expression => { parse_binop(pair, Expr::BoolEQ) }
        Rule::not_equal_expression => { parse_binop(pair, Expr::BoolNE) }
        Rule::application_expression => { parse_binop(pair, Expr::App) }

        Rule::selector_expression_raw =>
            parse!(pair; (first: expression, rest*: str) => {
                rest.fold_results(first, |acc, e| bx(Expr::Field(acc, e)))?
            }),

        Rule::identifier_raw =>
            parse!(pair; (name: str, idx?: natural) => {
                match Builtin::parse(name) {
                    Some(b) => bx(Expr::Builtin(b)),
                    None => match name {
                        "True" => bx(Expr::BoolLit(true)),
                        "False" => bx(Expr::BoolLit(false)),
                        name => bx(Expr::Var(V(name, idx.unwrap_or(0)))),
                    }
                }
            }),

        Rule::ifthenelse_expression =>
            parse!(pair; (cond: expression, left: expression, right: expression) => {
                bx(Expr::BoolIf(cond, left, right))
            }),


        // Rule::record_type_or_literal => {
        //     let mut inner = pair.into_inner();
        //     let first_expr = parse_expression(inner.next().unwrap());
        //     inner.fold(first_expr, |acc, e| bx(Expr::Field(acc, e.as_str())))
        // }

        _ => {
            let rulename = format!("{:?}", pair.as_rule());
            parse!(pair; (exprs*: expression) => {
                bx(Expr::FailedParse(rulename, exprs.map_results(|x| *x).collect::<ParseResult<_>>()?))
            })
        }
    }
}

pub fn parse_expr_pest(s: &str) -> ParseResult<BoxExpr>  {
    let parsed_expr = DhallParser::parse(Rule::final_expression, s)?.next().unwrap();

    parse_expression(parsed_expr)
}


#[test]
fn test_parse() {
    use crate::core::Expr::*;
    // let expr = r#"{ x = "foo", y = 4 }.x"#;
    // let expr = r#"(1 + 2) * 3"#;
    let expr = r#"if True then 1 + 3 * 5 else 2"#;
    println!("{:?}", parse_expr_lalrpop(expr));
    match parse_expr_pest(expr) {
        Err(e) => {
            println!("{:?}", e);
            println!("{}", e);
        },
        ok => println!("{:?}", ok),
    }
    assert_eq!(parse_expr_pest(expr).unwrap(), parse_expr_lalrpop(expr).unwrap());
    assert!(false);

    println!("test {:?}", parse_expr_lalrpop("3 + 5 * 10"));
    assert!(parse_expr_lalrpop("22").is_ok());
    assert!(parse_expr_lalrpop("(22)").is_ok());
    assert_eq!(parse_expr_lalrpop("3 + 5 * 10").ok(),
               Some(Box::new(NaturalPlus(Box::new(NaturalLit(3)),
                                Box::new(NaturalTimes(Box::new(NaturalLit(5)),
                                                      Box::new(NaturalLit(10))))))));
    // The original parser is apparently right-associative
    assert_eq!(parse_expr_lalrpop("2 * 3 * 4").ok(),
               Some(Box::new(NaturalTimes(Box::new(NaturalLit(2)),
                                 Box::new(NaturalTimes(Box::new(NaturalLit(3)),
                                                       Box::new(NaturalLit(4))))))));
    assert!(parse_expr_lalrpop("((((22))))").is_ok());
    assert!(parse_expr_lalrpop("((22)").is_err());
    println!("{:?}", parse_expr_lalrpop("\\(b : Bool) -> b == False"));
    assert!(parse_expr_lalrpop("\\(b : Bool) -> b == False").is_ok());
    println!("{:?}", parse_expr_lalrpop("foo.bar"));
    assert!(parse_expr_lalrpop("foo.bar").is_ok());
    assert!(parse_expr_lalrpop("[] : List Bool").is_ok());

    // println!("{:?}", parse_expr_lalrpop("< Left = True | Right : Natural >"));
    // println!("{:?}", parse_expr_lalrpop(r#""bl${42}ah""#));
    // assert!(parse_expr_lalrpop("< Left = True | Right : Natural >").is_ok());
}