summaryrefslogtreecommitdiff
path: root/chomp-macro/src/lib.rs
blob: 67964ecd6ec82de7709b3a3989f9caa72d3be0da (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
use chomp::{
    chomp::{
        ast::substitute::InlineCalls,
        typed::{
            context::Context,
            lower::{Backend, GenerateCode},
            TypeInfer,
        },
        visit::Visitable,
    },
    lower::RustBackend,
    nibble::File,
};
use proc_macro::TokenStream;
use syn::Error;

#[proc_macro]
pub fn nibble(item: TokenStream) -> TokenStream {
    syn::parse(item)
        .and_then(|nibble: File| nibble.convert().map_err(Error::from))
        .and_then(|(funs, goal)| {
            funs.into_iter()
                .try_rfold(goal, |goal, function| {
                    goal.fold(&mut InlineCalls { function })
                })
                .map_err(Error::from)
        })
        .and_then(|expr| {
            let mut context = Context::default();
            expr.fold(&mut TypeInfer {
                context: &mut context,
            })
            .map_err(Error::from)
        })
        .map(|typed| {
            let mut backend = RustBackend::default();
            let id = typed.gen(&mut backend);
            backend.emit_code(None, None, id)
        })
        .unwrap_or_else(Error::into_compile_error)
        .into()
}