Skip to main content

graphics_bindgen/
enumeration.rs

1use proc_macro2::{Literal, TokenStream};
2use quote::{ToTokens, quote};
3use syn::{Ident, Signature};
4
5use crate::{Call, function::get_function_identifier, naming::snake_ident_to_upper_camel};
6
7pub fn get_variant_identifier(identifier: &Ident) -> Ident {
8    let identifier = get_function_identifier("", identifier);
9    snake_ident_to_upper_camel(&identifier)
10}
11
12pub fn generate_code(signatures: Vec<Signature>) -> TokenStream {
13    let catalog = crate::CallCatalog::from_signatures(signatures).expect("invalid graphics ABI");
14    let calls: Vec<_> = catalog.calls().iter().collect();
15    generate_calls(&calls)
16}
17
18/// Generate the guest enum from an already numbered catalog subset.
19/// Unlike `generate_code`, this preserves the original catalog IDs.
20pub fn generate_calls(calls: &[&Call]) -> TokenStream {
21    let variants = &calls
22        .iter()
23        .map(|call| {
24            let identifier = get_variant_identifier(&call.signature.ident);
25            let value = Literal::usize_unsuffixed(call.id as usize);
26
27            quote! { #identifier = #value }
28        })
29        .collect::<Vec<_>>();
30
31    quote! {
32        #[derive(Debug, Copy, Clone, PartialEq, Eq)]
33        #[allow(dead_code)]
34        #[repr(u16)]
35        pub enum FunctionCall {
36            #(
37                #variants,
38            )*
39        }
40    }
41    .to_token_stream()
42}