summary refs log tree commit diff
path: root/opcode_proc/src/lib.rs
blob: 7c84f9af7d5647ff051f3979bceade84d77a3118 (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
extern crate proc_macro;
extern crate syn;
extern crate quote;
extern crate proc_macro2;

use proc_macro::TokenStream;
use quote::quote;
use proc_macro2::Span;
use syn::{braced, bracketed, parenthesized, parse::{Parse, ParseStream}, parse_macro_input, punctuated::Punctuated, token::{self, Paren}, Block, Error, PatType, Ident, LitInt, Result, Token, Type, TypeTuple};

#[proc_macro]
pub fn generate_opcodes(item: TokenStream) -> TokenStream {
    let ops_def = parse_macro_input!(item as OpcodeBlock);

    let enum_name = ops_def.enum_name;
    let field_names = ops_def.codes.iter().map(|field| &field.name).collect::<Vec<_>>();

    let getcode_match_arms = ops_def.codes.iter().map(|field| {
        let code = &field.byte_code;
        let variant = &field.name;
        quote! {
            #code => Some(Self::#variant),
        }
    }).collect::<Vec<_>>();

    let getinput_match_arms = ops_def.codes.iter().map(|field| {
        let variant = &field.name;
        let num = &field.input_params.len();
        quote! {
            #enum_name::#variant => #num,
        }
    });

    let getoutput_match_arms = ops_def.codes.iter().map(|field| {
        let variant = &field.name;
        let num = &field.output_params.len();
        quote! {
            #enum_name::#variant => #num,
        }
    });

    let gen_stub_arms = ops_def.codes.iter().map(|field| {
        let variant = &field.name;
        let value = &field.no_store;
        quote! {
            #enum_name::#variant => #value,
        }
    });

    let closure_match_arms = ops_def.codes.iter().map(|field| {
        let variant = &field.name;
        let closure_expr = &field.func_block;
        let interpreter_arg = &field.interpreter_ident.clone().unwrap_or(Ident::new("_terp", Span::call_site()));
        let input_args = &field.input_params;
        let output_args = if field.output_params.len() == 1 {
            let arg = field.output_params[0].clone();
            quote! { #arg }
        } else {
            let args = &field.output_params;
            quote! { (#(#args),*) }
        };


        let call_args = if field.input_params.len() > 0 {
            let arg_expr = (0..field.input_params.len()).map(|index| quote! {input_params[#index]}).collect::<Vec<_>>();
            quote! {interpreter, #(#arg_expr),*}
        } else {
            quote! {interpreter}
        };

        let return_vec = (0..field.output_params.len()).map(|index| quote! {out_tuple.#index});
        let call = match field.output_params.len() {
            0 => quote! {
                closure(#call_args);
                return Vec::new();
            },
            1 => quote! {
                let result = closure(#call_args);
                return vec![ result ];
            },
            _ => quote! {
                let out_tuple = closure(#call_args);
                return vec![ #(#return_vec),* ];
            },
        };

        quote! {
            #enum_name::#variant => {
                let closure = |#interpreter_arg: &mut crate::Interpreter, #(#input_args),*| -> #output_args
                    #closure_expr;

                #call
            }
        }
    });

    let tokens = quote! {
        #[derive(Debug, Clone)]
        pub enum #enum_name {
            #(#field_names),*
        }

        impl #enum_name {
            pub fn get_from_code(code: u32) -> Option<Self> {
                match code {
                    #(#getcode_match_arms)*
                    _ => None
                }
            }

            pub fn get_input_arg_count(opcode: Self) -> usize {
                match opcode {
                    #(#getinput_match_arms)*
                }
            }

            pub fn get_output_arg_count(opcode: Self) -> usize {
                match opcode {
                    #(#getoutput_match_arms)*
                }
            }

            pub fn should_gen_return_stub(opcode: Self) -> bool {
                match opcode {
                    #(#gen_stub_arms)*
                }
            }

            pub fn call_opcode(interpreter: &mut crate::Interpreter, opcode: Self, input_params: Vec<u32>) -> Vec<u32> {
                match opcode {
                    #(#closure_match_arms)*
                }
            }
        }
    };

    tokens.into()
}

impl Parse for OpcodeBlock {
    fn parse(input: ParseStream) -> Result<Self> {
        let inner;
        input.parse::<Token![pub]>()?;
        Ok(OpcodeBlock {
            enum_token: input.parse()?,
            enum_name: input.parse()?,
            brace_token: braced!(inner in input),
            codes: inner.parse_terminated(SingleOpcodeDefinition::parse, Token![,])?,
        })
    }
}

impl Parse for SingleOpcodeDefinition {
    fn parse(input: ParseStream) -> Result<Self> {
        let attr;
        input.parse::<Token![#]>()?;
        bracketed!(attr in input);
        let code = attr.parse::<Ident>()?;
        if code != "code" {
            return Err(Error::new(code.span(), "expected `code` attribute"));
        }
        let code;
        parenthesized!(code in attr);
        let byte_code = code.parse::<LitInt>()?;

        let mut no_store = false;
        if attr.peek(Token![,]) {
            attr.parse::<Token![,]>()?;
            let extra_attr = attr.parse::<Ident>()?;
            if extra_attr == "no_store" {
                no_store = true;
            }
        }

        input.parse::<Token![fn]>()?;
        let name = input.parse::<Ident>()?;

        let params;
        let mut interpreter_ident = None;
        parenthesized!(params in input);
        if params.peek(Token![&]) {
            params.parse::<Token![&]>()?;
            params.parse::<Token![mut]>()?;
            interpreter_ident = Some(params.parse::<Ident>()?);

            if params.peek(Token![,]) {
                params.parse::<Token![,]>()?;
            }
        }

        let input_params = params.parse_terminated(PatType::parse, Token![,])?
            .into_iter().map(|param| param).collect();

        let output_params;
        if input.peek(Token![->]) {
            input.parse::<Token![->]>()?;

            if input.peek(Paren) {
                let params;
                parenthesized!(params in input);
                output_params = params.parse_terminated(Type::parse, Token![,])?.into_iter().map(|s| s).collect::<Vec<_>>();
            } else {
                output_params = vec![input.parse::<Type>()?]
            }
        } else {
            output_params = Vec::new();
        }

        let func_block = input.parse::<Block>()?;

        Ok(SingleOpcodeDefinition {
            byte_code,
            no_store,
            name,
            input_params,
            interpreter_ident,
            output_params,
            func_block,
        })
    }
}

struct OpcodeBlock {
    pub enum_token: token::Enum,
    pub enum_name: Ident,
    pub brace_token: token::Brace,
    pub codes: Punctuated<SingleOpcodeDefinition, Token![,]>,
}

struct SingleOpcodeDefinition {
    pub byte_code: LitInt,
    pub no_store: bool,
    pub name: Ident,
    pub interpreter_ident: Option<Ident>,
    pub input_params: Vec<PatType>,
    pub output_params: Vec<Type>,
    pub func_block: Block,
}