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
extern crate proc_macro;

use expry::memorypool::*;
use expry::*;

use litrs::StringLit;

use quote::*;

fn first_string(tokens: proc_macro2::TokenStream) -> String {
    for i in tokens {
        if let Ok(lit) = StringLit::try_from(i) {
            return lit.value().to_string();
        }
    }
    String::new()
}

#[proc_macro]
pub fn expry(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
    let input = proc_macro2::TokenStream::from(input);
    let expr = first_string(input);

    let mut allocator = MemoryPool::new();
    let mut scope = allocator.rewind();
    let bytecode = expry_compile(&expr, None, &mut scope);
    match bytecode {
        Ok(bytecode) => {
            let lit = proc_macro2::Literal::byte_string(bytecode.get());
            quote!{ expry::BytecodeRef(#lit) }.into()
        },
        Err(err) => {
            let msg = expry_compile_error_format_short(&expr, &err);
            compile_error_as_expr(&msg)
        },
    }
}

// warning is not supported yet: https://github.com/rust-lang/rust/issues/54140
#[allow(dead_code)]
fn compile_error(string: &str) -> proc_macro::TokenStream {
    let expanded = quote!(
        compile_error!(#string);
        );
    proc_macro::TokenStream::from(expanded)
}

fn compile_error_as_expr(string: &str) -> proc_macro::TokenStream {
    let expanded = quote!(
        compile_error!(#string)
        );
    proc_macro::TokenStream::from(expanded)
}

#[cfg(nightly_build)]
#[allow(dead_code)]
fn compile_warning(span: proc_macro2::Span, message: &str) {
    Diagnostic::spanned(span.unwrap(), proc_macro::Level::Warning, message)
    .emit();
}
#[cfg(not(nightly_build))]
#[allow(dead_code)]
fn compile_warning(_span: proc_macro2::Span, _message: &str) {
}

#[cfg(nightly_build)]
#[allow(dead_code)]
fn compile_error_at(span: proc_macro2::Span, message: &str) {
    Diagnostic::spanned(span.unwrap(), proc_macro::Level::Error, message)
    .emit();
}
#[cfg(not(nightly_build))]
#[allow(dead_code)]
fn compile_error_at(_span: proc_macro2::Span, _message: &str) {
}


#[cfg(test)]
mod tests {
}