Skip to main content

tinyscript_derive/
lib.rs

1// Copyright © 2025 Stephan Kunz
2//! Derive macro [`ScriptEnum`].
3
4#[doc(hidden)]
5extern crate proc_macro;
6
7#[doc(hidden)]
8extern crate alloc;
9
10use proc_macro2::TokenStream;
11use quote::quote;
12use syn::{DeriveInput, Expr, Lit};
13
14/// Implementation of the derive macro [`ScriptEnum`]
15fn derive_scripting_enum(input: &DeriveInput) -> TokenStream {
16	// structure name
17	let ident = &input.ident;
18
19	// Check type of input and handle enums
20	let mut discriminant = -1_i8;
21	let variants: Vec<(String, i8)> = match &input.data {
22		syn::Data::Enum(data) => data
23			.variants
24			.iter()
25			.map(|v| {
26				if let Some((_eq, expr)) = &v.discriminant {
27					match expr {
28						Expr::Lit(expr_lit) => match &expr_lit.lit {
29							Lit::Int(lit_int) => {
30								discriminant = lit_int
31									.base10_parse::<i8>()
32									.expect("value must be i8");
33							}
34							_ => panic!("value must be i8"),
35						},
36						_ => panic!("value must be i8"),
37					}
38				} else {
39					discriminant += 1;
40				}
41				(v.ident.to_string(), discriminant)
42			})
43			.collect(),
44		syn::Data::Struct(_struct) => panic!("structs not supported by ScriptEnum"),
45		syn::Data::Union(_union) => panic!("unions not supported by ScriptEnum"),
46	};
47	let variant_keys: Vec<String> = variants.iter().map(|v| v.0.clone()).collect();
48	let variant_discriminants: Vec<i8> = variants.iter().map(|v| v.1).collect();
49
50	//
51	let (impl_generics, type_generics, where_clause) = input.generics.split_for_impl();
52
53	let derived: TokenStream = "#[automatically_derived]"
54		.parse()
55		.expect("derive(ScriptEnum) - derived");
56	let diagnostic: TokenStream = "#[diagnostic::do_not_recommend]"
57		.parse()
58		.expect("derive(ScriptEnum) - diagnostic");
59
60	quote! {
61		#derived
62		#diagnostic
63		impl #impl_generics tinyscript::ScriptEnum for #ident #type_generics #where_clause {
64			fn key_value_tuples<'a>() -> tinyscript::__private::Vec<(&'a str, i8)> {
65				tinyscript::__private::vec![#((#variant_keys, #variant_discriminants)),*]
66			}
67		}
68	}
69}
70
71/// Derive macro [`ScriptEnum`].
72/// Enables a Rust enum to be used in a 'C' like mannner within the `tinyscript` language.
73///
74/// The variants are numbered like Rust does: from 0, or continuing from an explicit discriminant.
75/// Explicit discriminants must be integer literals that fit into an `i8`.
76///
77/// # Usage
78/// ```no_test
79/// #[derive(ScriptEnum)]
80/// enum Color {
81///     Red,
82///     Green = 5,
83///     Blue,
84/// }
85///
86/// // make the variants known to the scripts
87/// for (name, discriminant) in Color::key_value_tuples() {
88///     runtime.register_enum_tuple(name, discriminant)?;
89/// }
90/// ```
91///
92/// # Result
93/// Expands the above enum to
94/// ```no_test
95/// enum Color {
96///     Red,
97///     Green = 5,
98///     Blue,
99/// }
100///
101/// #[automatically_derived]
102/// #[diagnostic::do_not_recommend]
103/// impl tinyscript::ScriptEnum for Color {
104///     fn key_value_tuples<'a>() -> tinyscript::__private::Vec<(&'a str, i8)> {
105///         tinyscript::__private::vec![("Red", 0), ("Green", 5), ("Blue", 6)]
106///     }
107/// }
108/// ```
109///
110/// # Panics
111/// - if used on structs or unions
112/// - if a discriminant is not an integer literal or does not fit into an `i8`
113#[proc_macro_derive(ScriptEnum, attributes(tscript))]
114pub fn derive_script_enum(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
115	// Construct a representation of Rust code as a syntax tree
116	let input: DeriveInput = syn::parse(input).expect("could not parse input");
117
118	derive_scripting_enum(&input).into()
119}
120
121#[cfg(test)]
122mod tests {
123	use super::*;
124	use syn::parse_quote;
125
126	fn expand(input: &DeriveInput) -> String {
127		derive_scripting_enum(input).to_string()
128	}
129
130	#[test]
131	fn variants_are_numbered_from_zero_or_explicit_discriminants() {
132		let input: DeriveInput = parse_quote! {
133			enum Color { Red, Green = 5, Blue }
134		};
135		let expanded = expand(&input);
136		assert!(expanded.contains("impl tinyscript :: ScriptEnum for Color"));
137		assert!(expanded.contains(r#"("Red" , 0i8) , ("Green" , 5i8) , ("Blue" , 6i8)"#));
138	}
139
140	#[test]
141	fn generics_are_kept() {
142		let input: DeriveInput = parse_quote! {
143			enum Wrapper<T: Clone> where T: Copy { A }
144		};
145		assert!(expand(&input).contains("impl < T : Clone > tinyscript :: ScriptEnum for Wrapper < T > where T : Copy"));
146	}
147
148	#[test]
149	#[should_panic(expected = "structs not supported by ScriptEnum")]
150	fn structs_are_rejected() {
151		let input: DeriveInput = parse_quote! { struct S; };
152		expand(&input);
153	}
154
155	#[test]
156	#[should_panic(expected = "unions not supported by ScriptEnum")]
157	fn unions_are_rejected() {
158		let input: DeriveInput = parse_quote! { union U { a: u8 } };
159		expand(&input);
160	}
161
162	#[test]
163	#[should_panic(expected = "value must be i8")]
164	fn discriminant_out_of_i8_range_is_rejected() {
165		let input: DeriveInput = parse_quote! { enum E { A = 200 } };
166		expand(&input);
167	}
168
169	#[test]
170	#[should_panic(expected = "value must be i8")]
171	fn non_integer_discriminant_is_rejected() {
172		let input: DeriveInput = parse_quote! { enum E { A = 'a' } };
173		expand(&input);
174	}
175
176	#[test]
177	#[should_panic(expected = "value must be i8")]
178	fn computed_discriminant_is_rejected() {
179		let input: DeriveInput = parse_quote! { enum E { A = 1 + 1 } };
180		expand(&input);
181	}
182}