summaryrefslogtreecommitdiff
path: root/src/nibble/mod.rs
blob: bb14f7bb8ac733543e37efe0f967d15baecb3841 (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
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
use crate::ast::{
    self,
    convert::{Context, Convert},
};
use proc_macro2::Span;
use syn::{
    ext::IdentExt,
    parse::{Parse, ParseStream},
    punctuated::{Pair, Punctuated},
    token, Result, Token,
};

const PREFER_SUBST_OVER_CALL: bool = true;

pub type Epsilon = Token![_];

impl Convert for Epsilon {
    fn convert(&self, _: &mut Context) -> ast::Term {
        ast::Term::Epsilon(*self)
    }
}

type Ident = syn::Ident;

impl Convert for Ident {
    fn convert(&self, context: &mut Context) -> ast::Term {
        use ast::Term;
        let name = self.to_string();

        if let Some(variable) = context.get_binding(&name) {
            Term::Variable(ast::Variable::new(self.clone(), variable))
        } else if PREFER_SUBST_OVER_CALL {
            if let Some(term) = context.get_variable(&name) {
                term.clone()
            } else if let Some(term) = context.call_function(&name, std::iter::empty()) {
                term
            } else {
                let span = self.span();
                Term::Call(ast::Call::new(self.clone(), Vec::new(), span))
            }
        } else {
            let span = self.span();
            Term::Call(ast::Call::new(self.clone(), Vec::new(), span))
        }
    }
}

type Literal = syn::LitStr;

impl Convert for Literal {
    fn convert(&self, _: &mut Context) -> ast::Term {
        ast::Term::Literal(self.clone())
    }
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Call {
    name: Ident,
    paren_tok: token::Paren,
    args: Punctuated<Expression, Token![,]>,
}

impl Call {
    fn span(&self) -> Span {
        self.name
            .span()
            .join(self.paren_tok.span)
            .unwrap_or_else(Span::call_site)
    }
}

impl Parse for Call {
    fn parse(input: ParseStream<'_>) -> Result<Self> {
        let args;
        let name = input.call(Ident::parse_any)?;
        let paren_tok = syn::parenthesized!(args in input);
        let args = args.call(Punctuated::parse_terminated)?;
        Ok(Self {
            name,
            paren_tok,
            args,
        })
    }
}

impl Convert for Call {
    fn convert(&self, context: &mut Context) -> ast::Term {
        use ast::Term;
        let args: Vec<_> = self
            .args
            .pairs()
            .map(|pair| match pair {
                Pair::Punctuated(t, _) => t.convert(context),
                Pair::End(t) => t.convert(context),
            })
            .collect();
        if PREFER_SUBST_OVER_CALL {
            if let Some(term) = context.call_function(&self.name.to_string(), args.clone()) {
                term
            } else {
                Term::Call(ast::Call::new(self.name.clone(), args, self.span()))
            }
        } else {
            Term::Call(ast::Call::new(self.name.clone(), args, self.span()))
        }
    }
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Fix {
    bracket_token: token::Bracket,
    arg: Ident,
    paren_token: token::Paren,
    expr: Expression,
}

impl Fix {
    fn span(&self) -> Span {
        self.bracket_token
            .span
            .join(self.paren_token.span)
            .unwrap_or_else(Span::call_site)
    }
}

impl Parse for Fix {
    fn parse(input: ParseStream<'_>) -> Result<Self> {
        let arg;
        let bracket_token = syn::bracketed!(arg in input);
        let arg = arg.call(Ident::parse_any)?;
        let expr;
        let paren_token = syn::parenthesized!(expr in input);
        let expr = expr.parse()?;
        Ok(Self {
            bracket_token,
            arg,
            paren_token,
            expr,
        })
    }
}

impl Convert for Fix {
    fn convert(&self, context: &mut Context) -> ast::Term {
        use ast::Term;
        let span = self.span();
        let expr = &self.expr;
        let arg_name = self.arg.to_string();
        Term::Fix(ast::Fix::new(
            self.arg.clone(),
            context.push_binding(arg_name, |c| expr.convert(c)),
            span,
        ))
    }
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ParenExpression {
    paren_tok: token::Paren,
    expr: Expression,
}

impl ParenExpression {
    pub fn span(&self) -> Span {
        self.paren_tok.span
    }
}

impl Parse for ParenExpression {
    fn parse(input: ParseStream<'_>) -> Result<Self> {
        let expr;
        let paren_tok = syn::parenthesized!(expr in input);
        let expr = expr.parse()?;
        Ok(Self { paren_tok, expr })
    }
}

impl Convert for ParenExpression {
    fn convert(&self, context: &mut Context) -> ast::Term {
        self.expr.convert(context)
    }
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub enum Term {
    Epsilon(Epsilon),
    Ident(Ident),
    Literal(Literal),
    Call(Call),
    Fix(Fix),
    Parens(ParenExpression),
}

impl Term {
    pub fn span(&self) -> Span {
        match self {
            Self::Epsilon(eps) => eps.span,
            Self::Ident(ident) => ident.span(),
            Self::Literal(lit) => lit.span(),
            Self::Call(call) => call.span(),
            Self::Fix(fix) => fix.span(),
            Self::Parens(paren) => paren.span(),
        }
    }
}

impl Parse for Term {
    fn parse(input: ParseStream<'_>) -> Result<Self> {
        let lookahead = input.lookahead1();
        if lookahead.peek(Token![_]) {
            input.parse().map(Self::Epsilon)
        } else if lookahead.peek(syn::LitStr) {
            input.parse().map(Self::Literal)
        } else if lookahead.peek(token::Bracket) {
            input.parse().map(Self::Fix)
        } else if lookahead.peek(token::Paren) {
            let content;
            let paren_tok = syn::parenthesized!(content in input);
            content
                .parse()
                .map(|expr| Self::Parens(ParenExpression { paren_tok, expr }))
        } else if lookahead.peek(Ident::peek_any) {
            let name = input.call(Ident::parse_any)?;
            if input.peek(token::Paren) {
                let args;
                let paren_tok = syn::parenthesized!(args in input);
                args.call(Punctuated::parse_terminated).map(|args| {
                    Self::Call(Call {
                        name,
                        paren_tok,
                        args,
                    })
                })
            } else {
                Ok(Self::Ident(name))
            }
        } else {
            Err(lookahead.error())
        }
    }
}

impl Convert for Term {
    fn convert(&self, context: &mut Context) -> ast::Term {
        match self {
            Self::Epsilon(e) => e.convert(context),
            Self::Ident(i) => i.convert(context),
            Self::Literal(l) => l.convert(context),
            Self::Call(c) => c.convert(context),
            Self::Fix(f) => f.convert(context),
            Self::Parens(e) => e.convert(context),
        }
    }
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Cat {
    terms: Punctuated<Term, Token![.]>,
}

impl Cat {
    pub fn span(&self) -> Span {
        let mut pairs = self.terms.pairs();
        let mut span = pairs.next().and_then(|pair| match pair {
            Pair::Punctuated(term, punct) => term.span().join(punct.span),
            Pair::End(term) => Some(term.span()),
        });

        for pair in pairs {
            span = span.and_then(|span| match pair {
                Pair::Punctuated(term, punct) => {
                    span.join(term.span()).and_then(|s| s.join(punct.span))
                }
                Pair::End(term) => span.join(term.span()),
            })
        }

        span.unwrap_or_else(Span::call_site)
    }
}

impl Parse for Cat {
    fn parse(input: ParseStream<'_>) -> Result<Self> {
        Ok(Self {
            terms: input.call(Punctuated::parse_separated_nonempty)?,
        })
    }
}

impl Convert for Cat {
    fn convert(&self, context: &mut Context) -> ast::Term {
        use ast::Term;
        let mut iter = self.terms.pairs();
        let init = match iter.next().unwrap() {
            Pair::Punctuated(t, p) => Ok((t.convert(context), p)),
            Pair::End(t) => Err(t.convert(context)),
        };
        iter.fold(init, |term, pair| {
            let (fst, punct) = term.unwrap();
            match pair {
                Pair::Punctuated(t, p) => {
                    Ok((Term::Cat(ast::Cat::new(fst, *punct, t.convert(context))), p))
                }
                Pair::End(t) => Err(Term::Cat(ast::Cat::new(fst, *punct, t.convert(context)))),
            }
        })
        .unwrap_err()
    }
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Alt {
    cats: Punctuated<Cat, Token![|]>,
}

impl Alt {
    pub fn span(&self) -> Span {
        let mut pairs = self.cats.pairs();
        let mut span = pairs.next().and_then(|pair| match pair {
            Pair::Punctuated(cat, punct) => cat.span().join(punct.span),
            Pair::End(cat) => Some(cat.span()),
        });

        for pair in pairs {
            span = span.and_then(|span| match pair {
                Pair::Punctuated(cat, punct) => {
                    span.join(cat.span()).and_then(|s| s.join(punct.span))
                }
                Pair::End(cat) => span.join(cat.span()),
            })
        }

        span.unwrap_or_else(Span::call_site)
    }
}

impl Parse for Alt {
    fn parse(input: ParseStream<'_>) -> Result<Self> {
        Ok(Self {
            cats: input.call(Punctuated::parse_separated_nonempty)?,
        })
    }
}

impl Convert for Alt {
    fn convert(&self, context: &mut Context) -> ast::Term {
        use ast::Term;
        let mut iter = self.cats.pairs();
        let init = match iter.next().unwrap() {
            Pair::Punctuated(t, p) => Ok((t.convert(context), p)),
            Pair::End(t) => Err(t.convert(context)),
        };
        iter.fold(init, |cat, pair| {
            let (left, punct) = cat.unwrap();
            match pair {
                Pair::Punctuated(t, p) => Ok((
                    Term::Alt(ast::Alt::new(left, *punct, t.convert(context))),
                    p,
                )),
                Pair::End(t) => Err(Term::Alt(ast::Alt::new(left, *punct, t.convert(context)))),
            }
        })
        .unwrap_err()
    }
}

pub type Expression = Alt;

#[cfg(test)]
mod tests {
    use super::{Epsilon, Ident, Literal};
    use syn::parse_str;

    #[test]
    fn parse_epsilon() {
        assert!(parse_str::<Epsilon>("_").is_ok());
    }

    #[test]
    fn parse_ident() {
        assert_eq!(parse_str::<Ident>("x").unwrap().to_string(), "x");
        assert_eq!(parse_str::<Ident>("x_yz").unwrap().to_string(), "x_yz");
        assert_eq!(parse_str::<Ident>("a123").unwrap().to_string(), "a123");
        assert_eq!(parse_str::<Ident>("𝒢𝒢").unwrap().to_string(), "𝒢𝒢");
        assert!(parse_str::<Ident>("1").is_err());
        assert!(parse_str::<Ident>("_").is_err());
    }

    #[test]
    fn parse_literal() {
        assert_eq!(parse_str::<Literal>(r#""hello""#).unwrap().value(), "hello")
    }
}