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
use nom::{alpha, digit, types::CompleteStr};
use nom::{
    alt, alt_sep, call_m, do_parse, error_position, expr_res, map, map_res, method, opt, sep,
    separated_list, tag, wrap_sep, ws,
};

#[allow(unused_imports)]
use nom::call; // FIXME see https://github.com/Geal/nom/pull/871

use std::marker::PhantomData;
use std::num::ParseIntError;

use crate::{Name, Type, TypeSchema};

#[derive(Debug)]
/// A failed parse.
pub struct ParseError;

impl std::fmt::Display for ParseError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "ParseError")
    }
}

impl std::error::Error for ParseError {}

pub fn parse_type<N: Name>(input: &str) -> Result<Type<N>, ParseError> {
    match Parser::default().monotype(CompleteStr(input)).1 {
        Ok((_, t)) => Ok(t),
        _ => Err(ParseError),
    }
}
pub fn parse_typeschema<N: Name>(input: &str) -> Result<TypeSchema<N>, ParseError> {
    match Parser::default().polytype(CompleteStr(input)).1 {
        Ok((_, t)) => Ok(t),
        _ => Err(ParseError),
    }
}

fn nom_usize(inp: CompleteStr<'_>) -> Result<usize, ParseIntError> {
    inp.parse()
}

// hack for polymorphism with nom
pub struct Parser<N: Name>(PhantomData<N>);
impl<N: Name> Default for Parser<N> {
    fn default() -> Self {
        Parser(PhantomData)
    }
}
impl<N: Name> Parser<N> {
    method!(
        var<Parser<N>, CompleteStr<'_>, Type<N>>,
        self,
        do_parse!(tag!("t") >> num: map_res!(digit, nom_usize) >> (Type::Variable(num)))
    );
    method!(
        constructed_simple<Parser<N>, CompleteStr<'_>, Type<N>>,
        self,
        do_parse!(
            name_raw: alpha
                >> name: expr_res!(N::parse(&name_raw))
                >> (Type::Constructed(name, vec![]))
        )
    );
    method!(constructed_complex<Parser<N>, CompleteStr<'_>, Type<N>>, mut self,
           do_parse!(
               name_raw: alpha >>
               name: expr_res!(N::parse(&name_raw)) >>
               tag!("(") >>
               args: separated_list!(tag!(","), ws!(call_m!(self.monotype))) >>
               tag!(")") >>
               (Type::Constructed(name, args)))
    );
    method!(arrow<Parser<N>, CompleteStr<'_>, Type<N>>, mut self,
           do_parse!(
               alpha: ws!(alt!(call_m!(self.parenthetical) |
                               call_m!(self.var) |
                               call_m!(self.constructed_complex) |
                               call_m!(self.constructed_simple))) >>
               alt!(tag!("→") | tag!("->")) >>
               beta: ws!(call_m!(self.monotype)) >>
               (Type::arrow(alpha, beta)))
    );
    method!(parenthetical<Parser<N>, CompleteStr<'_>, Type<N>>, mut self,
           do_parse!(
               tag!("(") >>
               interior: call_m!(self.arrow) >>
               tag!(")") >>
               (interior))
    );
    method!(binding<Parser<N>, CompleteStr<'_>, TypeSchema<N>>, mut self,
           do_parse!(
               opt!(tag!("∀")) >>
               tag!("t") >>
               variable: map_res!(digit, nom_usize) >>
               ws!(tag!(".")) >>
               body: map!(call_m!(self.polytype), Box::new) >>
               (TypeSchema::Polytype{variable, body}))
    );
    method!(monotype<Parser<N>, CompleteStr<'_>, Type<N>>, mut self,
           alt!(call_m!(self.arrow) |
                call_m!(self.var) |
                call_m!(self.constructed_complex) |
                call_m!(self.constructed_simple))
    );
    method!(polytype<Parser<N>, CompleteStr<'_>, TypeSchema<N>>, mut self,
        alt!(call_m!(self.binding) |
             map!(call_m!(self.monotype), TypeSchema::Monotype))
    );
}
impl<N: Name> TypeSchema<N> {
    /// Parse a [`TypeSchema`] from a string. This round-trips with [`Display`].
    /// This is a **leaky** operation and should be avoided wherever possible:
    /// names of constructed types will remain until program termination.
    ///
    /// The "for-all" `∀` is optional.
    ///
    /// # Examples
    ///
    /// ```
    /// # use polytype::{ptp, tp, TypeSchema};
    /// let t_par = TypeSchema::parse("∀t0. t0 -> t0").expect("valid type");
    /// let t_lit = ptp!(0; @arrow[tp!(0), tp!(0)]);
    /// assert_eq!(t_par, t_lit);
    ///
    /// let s = "∀t0. ∀t1. (t1 → t0 → t1) → t1 → list(t0) → t1";
    /// let t: TypeSchema<&'static str> = TypeSchema::parse(s).expect("valid type");
    /// let round_trip = t.to_string();
    /// assert_eq!(s, round_trip);
    /// ```
    ///
    /// [`Display`]: https://doc.rust-lang.org/std/fmt/trait.Display.html
    /// [`TypeSchema`]: enum.TypeSchema.html
    pub fn parse(s: &str) -> Result<TypeSchema<N>, ParseError> {
        parse_typeschema(s)
    }
}
impl<N: Name> Type<N> {
    /// Parse a type from a string. This round-trips with [`Display`]. This is a
    /// **leaky** operation and should be avoided wherever possible: names of
    /// constructed types will remain until program termination.
    ///
    /// # Examples
    ///
    /// ```
    /// # use polytype::{tp, Type};
    /// let t_par = Type::parse("int -> hashmap(str, list(bool))").expect("valid type");
    /// let t_lit = tp!(@arrow[
    ///     tp!(int),
    ///     tp!(hashmap(
    ///         tp!(str),
    ///         tp!(list(tp!(bool))),
    ///     )),
    /// ]);
    /// assert_eq!(t_par, t_lit);
    ///
    /// let s = "(t1 → t0 → t1) → t1 → list(t0) → t1";
    /// let t: Type<&'static str> = Type::parse(s).expect("valid type");
    /// let round_trip = t.to_string();
    /// assert_eq!(s, round_trip);
    /// ```
    ///
    /// [`Display`]: https://doc.rust-lang.org/std/fmt/trait.Display.html
    pub fn parse(s: &str) -> Result<Type<N>, ParseError> {
        parse_type(s)
    }
}