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
#![doc = include_str!("../README.md")]

use einsum_codegen::{codegen::ndarray::*, *};
use proc_macro::TokenStream;
use proc_macro2::TokenStream as TokenStream2;
use proc_macro_error::{abort_call_site, proc_macro_error};
use quote::quote;
use std::collections::BTreeSet;
use syn::parse::Parser;

/// proc-macro based einsum
#[proc_macro_error]
#[proc_macro]
pub fn einsum(input: TokenStream) -> TokenStream {
    einsum2(input.into()).into()
}

fn einsum2(input: TokenStream2) -> TokenStream2 {
    let (subscripts, args) = parse(input);
    let arg_ident: Vec<_> = (0..args.len()).map(Position::Arg).collect();
    let path = Path::brute_force(&subscripts).expect("Failed to construct execution path");
    let mut defined = BTreeSet::new();
    let fn_defs: Vec<_> = path
        .iter()
        .filter_map(|ss| {
            if defined.contains(&ss.escaped_ident()) {
                None
            } else {
                defined.insert(ss.escaped_ident());
                let inner = naive::inner(ss);
                Some(function_definition(ss, inner))
            }
        })
        .collect();
    let out = path.output();
    if path.num_args() != args.len() {
        abort_call_site!(
            "Argument number mismatch: subscripts ({}), args ({})",
            path.num_args(),
            args.len()
        )
    }

    quote! {
        {
            #(#fn_defs)*
            #(let #arg_ident = #args;)*
            #(#path)*
            #out
        }
    }
}

fn parse(input: TokenStream2) -> (String, Vec<syn::Expr>) {
    let parser = syn::punctuated::Punctuated::<syn::Expr, syn::Token![,]>::parse_terminated;
    let args = parser.parse2(input).expect("Invalid input for einsum!");
    let mut iter = args.into_iter();
    let subscripts = if let Some(syn::Expr::Lit(syn::ExprLit {
        lit: syn::Lit::Str(lit),
        attrs: _,
    })) = iter.next()
    {
        lit.value()
    } else {
        panic!("einsum! must start with subscript string literal")
    };
    let args = iter.collect::<Vec<_>>();
    (subscripts, args)
}

#[cfg(test)]
mod test {
    use super::*;
    use einsum_codegen::codegen::format_block;
    use std::str::FromStr;

    #[test]
    fn test_parse() {
        let input = TokenStream2::from_str(r#""ab,bc->ac", x, y"#).unwrap();
        let (subscripts, exprs) = parse(input);
        assert_eq!(subscripts, "ab,bc->ac");
        assert_eq!(exprs.len(), 2);
        assert_eq!(exprs[0], syn::parse_str::<syn::Expr>("x").unwrap());
        assert_eq!(exprs[1], syn::parse_str::<syn::Expr>("y").unwrap());
    }

    #[test]
    fn einsum_ab_bc() {
        let input = TokenStream2::from_str(r#""ab,bc->ac", x, y"#).unwrap();
        let tt = format_block(einsum2(input).to_string());
        insta::assert_snapshot!(tt, @r###"
        {
            fn ab_bc__ac<T, S0, S1>(
                arg0: ndarray::ArrayBase<S0, ndarray::Ix2>,
                arg1: ndarray::ArrayBase<S1, ndarray::Ix2>,
            ) -> ndarray::Array<T, ndarray::Ix2>
            where
                T: ndarray::LinalgScalar,
                S0: ndarray::Data<Elem = T>,
                S1: ndarray::Data<Elem = T>,
            {
                let (n_a, n_b) = arg0.dim();
                let (_, n_c) = arg1.dim();
                {
                    let (n_0, n_1) = arg0.dim();
                    assert_eq!(n_0, n_a);
                    assert_eq!(n_1, n_b);
                }
                {
                    let (n_0, n_1) = arg1.dim();
                    assert_eq!(n_0, n_b);
                    assert_eq!(n_1, n_c);
                }
                let mut out0 = ndarray::Array::zeros((n_a, n_c));
                for a in 0..n_a {
                    for c in 0..n_c {
                        for b in 0..n_b {
                            out0[(a, c)] = arg0[(a, b)] * arg1[(b, c)];
                        }
                    }
                }
                out0
            }
            let arg0 = x;
            let arg1 = y;
            let out0 = ab_bc__ac(arg0, arg1);
            out0
        }
        "###);
    }

    #[test]
    fn einsum_ab_bc_cd() {
        let input = TokenStream2::from_str(r#""ab,bc,cd->ad", x, y, z"#).unwrap();
        let tt = format_block(einsum2(input).to_string());
        insta::assert_snapshot!(tt, @r###"
        {
            fn ab_bc__ac<T, S0, S1>(
                arg0: ndarray::ArrayBase<S0, ndarray::Ix2>,
                arg1: ndarray::ArrayBase<S1, ndarray::Ix2>,
            ) -> ndarray::Array<T, ndarray::Ix2>
            where
                T: ndarray::LinalgScalar,
                S0: ndarray::Data<Elem = T>,
                S1: ndarray::Data<Elem = T>,
            {
                let (n_a, n_b) = arg0.dim();
                let (_, n_c) = arg1.dim();
                {
                    let (n_0, n_1) = arg0.dim();
                    assert_eq!(n_0, n_a);
                    assert_eq!(n_1, n_b);
                }
                {
                    let (n_0, n_1) = arg1.dim();
                    assert_eq!(n_0, n_b);
                    assert_eq!(n_1, n_c);
                }
                let mut out1 = ndarray::Array::zeros((n_a, n_c));
                for a in 0..n_a {
                    for c in 0..n_c {
                        for b in 0..n_b {
                            out1[(a, c)] = arg0[(a, b)] * arg1[(b, c)];
                        }
                    }
                }
                out1
            }
            let arg0 = x;
            let arg1 = y;
            let arg2 = z;
            let out1 = ab_bc__ac(arg0, arg1);
            let out0 = ab_bc__ac(out1, arg2);
            out0
        }
        "###);
    }
}