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, ExprLit, ExprUnary, Fields, Lit, LitInt, UnOp};
13
14/// The error for a discriminant that is no integer literal fitting into an `i8`.
15fn discriminant_error(expr: &Expr) -> syn::Error {
16	syn::Error::new_spanned(
17		expr,
18		"discriminant must be an integer literal that fits into an `i8`, e.g. `5` or `-3`; \
19		 constants and computations are not supported",
20	)
21}
22
23/// The value of an explicit discriminant: an integer literal, optionally negated.
24fn explicit_discriminant(expr: &Expr) -> syn::Result<i8> {
25	let parse = |literal: &LitInt, negative: bool| {
26		let digits = literal.base10_digits();
27		// parse with the sign, so that `-128` fits
28		let text = if negative { format!("-{digits}") } else { digits.to_owned() };
29		text.parse::<i8>()
30			.map_err(|_| discriminant_error(expr))
31	};
32	match expr {
33		Expr::Lit(ExprLit {
34			lit: Lit::Int(literal), ..
35		}) => parse(literal, false),
36		Expr::Unary(ExprUnary {
37			op: UnOp::Neg(_),
38			expr: operand,
39			..
40		}) => match &**operand {
41			Expr::Lit(ExprLit {
42				lit: Lit::Int(literal), ..
43			}) => parse(literal, true),
44			_ => Err(discriminant_error(expr)),
45		},
46		_ => Err(discriminant_error(expr)),
47	}
48}
49
50/// Implementation of the derive macro [`ScriptEnum`]
51fn derive_scripting_enum(input: &DeriveInput) -> syn::Result<TokenStream> {
52	// structure name
53	let ident = &input.ident;
54
55	let data = match &input.data {
56		syn::Data::Enum(data) => data,
57		syn::Data::Struct(data) => {
58			return Err(syn::Error::new_spanned(
59				data.struct_token,
60				"`ScriptEnum` supports only enums, not structs",
61			));
62		}
63		syn::Data::Union(data) => {
64			return Err(syn::Error::new_spanned(
65				data.union_token,
66				"`ScriptEnum` supports only enums, not unions",
67			));
68		}
69	};
70
71	// the variants are numbered like Rust does: from 0, or continuing from an explicit discriminant;
72	// `None` once the next implicit discriminant would exceed `i8::MAX`
73	let mut next = Some(0_i8);
74	let mut variant_keys = Vec::new();
75	let mut variant_discriminants = Vec::new();
76	for variant in &data.variants {
77		if !matches!(variant.fields, Fields::Unit) {
78			return Err(syn::Error::new_spanned(
79				&variant.fields,
80				"`ScriptEnum` variants must not have fields",
81			));
82		}
83		let discriminant = match &variant.discriminant {
84			Some((_eq, expr)) => explicit_discriminant(expr)?,
85			None => next.ok_or_else(|| {
86				syn::Error::new_spanned(&variant.ident, "the implicit discriminant of this variant exceeds `i8::MAX`")
87			})?,
88		};
89		next = discriminant.checked_add(1);
90		variant_keys.push(variant.ident.to_string());
91		variant_discriminants.push(discriminant);
92	}
93
94	//
95	let (impl_generics, type_generics, where_clause) = input.generics.split_for_impl();
96
97	let derived: TokenStream = "#[automatically_derived]"
98		.parse()
99		.expect("derive(ScriptEnum) - derived");
100	let diagnostic: TokenStream = "#[diagnostic::do_not_recommend]"
101		.parse()
102		.expect("derive(ScriptEnum) - diagnostic");
103
104	Ok(quote! {
105		#derived
106		#diagnostic
107		impl #impl_generics tinyscript::ScriptEnum for #ident #type_generics #where_clause {
108			fn key_value_tuples<'a>() -> tinyscript::__private::Vec<(&'a str, i8)> {
109				tinyscript::__private::vec![#((#variant_keys, #variant_discriminants)),*]
110			}
111		}
112	})
113}
114
115/// Derive macro [`ScriptEnum`].
116/// Enables a Rust enum to be used in a 'C' like mannner within the `tinyscript` language.
117///
118/// The variants are numbered like Rust does: from 0, or continuing from an explicit discriminant.
119/// Explicit discriminants must be integer literals that fit into an `i8`, negative ones included,
120/// e.g. `-3`; the variants must have no fields.
121///
122/// # Usage
123/// ```no_test
124/// #[derive(ScriptEnum)]
125/// enum Color {
126///     Red,
127///     Green = 5,
128///     Blue,
129/// }
130///
131/// // make the variants known to the scripts
132/// for (name, discriminant) in Color::key_value_tuples() {
133///     runtime.register_enum_tuple(name, discriminant)?;
134/// }
135/// ```
136///
137/// # Result
138/// Expands the above enum to
139/// ```no_test
140/// enum Color {
141///     Red,
142///     Green = 5,
143///     Blue,
144/// }
145///
146/// #[automatically_derived]
147/// #[diagnostic::do_not_recommend]
148/// impl tinyscript::ScriptEnum for Color {
149///     fn key_value_tuples<'a>() -> tinyscript::__private::Vec<(&'a str, i8)> {
150///         tinyscript::__private::vec![("Red", 0), ("Green", 5), ("Blue", 6)]
151///     }
152/// }
153/// ```
154///
155/// # Errors
156/// Compilation errors, pointing at the cause:
157/// - if used on structs or unions
158/// - if a variant has fields
159/// - if a discriminant is not an integer literal or does not fit into an `i8`
160/// - if an implicit discriminant would exceed `i8::MAX`
161#[proc_macro_derive(ScriptEnum)]
162pub fn derive_script_enum(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
163	// Construct a representation of Rust code as a syntax tree
164	let input = syn::parse_macro_input!(input as DeriveInput);
165
166	derive_scripting_enum(&input)
167		.unwrap_or_else(syn::Error::into_compile_error)
168		.into()
169}
170
171#[cfg(test)]
172mod tests {
173	use super::*;
174	use syn::parse_quote;
175
176	fn expand(input: &DeriveInput) -> String {
177		derive_scripting_enum(input).unwrap().to_string()
178	}
179
180	fn error(input: &DeriveInput) -> String {
181		derive_scripting_enum(input)
182			.unwrap_err()
183			.to_string()
184	}
185
186	#[test]
187	fn variants_are_numbered_from_zero_or_explicit_discriminants() {
188		let input: DeriveInput = parse_quote! {
189			enum Color { Red, Green = 5, Blue }
190		};
191		let expanded = expand(&input);
192		assert!(expanded.contains("impl tinyscript :: ScriptEnum for Color"));
193		assert!(expanded.contains(r#"("Red" , 0i8) , ("Green" , 5i8) , ("Blue" , 6i8)"#));
194	}
195
196	#[test]
197	fn negative_discriminants_and_the_limits_of_i8() {
198		let input: DeriveInput = parse_quote! {
199			enum E { A = -128, B, C = -1, D, E = 126, F }
200		};
201		assert!(
202			expand(&input).contains(
203				r#"("A" , - 128i8) , ("B" , - 127i8) , ("C" , - 1i8) , ("D" , 0i8) , ("E" , 126i8) , ("F" , 127i8)"#
204			)
205		);
206	}
207
208	#[test]
209	fn generics_are_kept() {
210		let input: DeriveInput = parse_quote! {
211			enum Wrapper<T: Clone> where T: Copy { A }
212		};
213		assert!(expand(&input).contains("impl < T : Clone > tinyscript :: ScriptEnum for Wrapper < T > where T : Copy"));
214	}
215
216	#[test]
217	fn structs_and_unions_are_rejected() {
218		let input: DeriveInput = parse_quote! { struct S; };
219		assert_eq!(error(&input), "`ScriptEnum` supports only enums, not structs");
220		let input: DeriveInput = parse_quote! { union U { a: u8 } };
221		assert_eq!(error(&input), "`ScriptEnum` supports only enums, not unions");
222	}
223
224	#[test]
225	fn variants_with_fields_are_rejected() {
226		for input in [
227			parse_quote! { enum E { A(u8) } },
228			parse_quote! { enum E { A, B { x: u8 } } },
229		] {
230			assert_eq!(error(&input), "`ScriptEnum` variants must not have fields");
231		}
232	}
233
234	#[test]
235	fn implicit_discriminant_beyond_i8_is_rejected() {
236		let input: DeriveInput = parse_quote! { enum E { A = 127, B } };
237		assert_eq!(error(&input), "the implicit discriminant of this variant exceeds `i8::MAX`");
238	}
239
240	#[test]
241	fn invalid_explicit_discriminants_are_rejected() {
242		for input in [
243			parse_quote! { enum E { A = 128 } },
244			parse_quote! { enum E { A = -129 } },
245			parse_quote! { enum E { A = 'a' } },
246			parse_quote! { enum E { A = 1 + 1 } },
247			parse_quote! { enum E { A = -X } },
248			parse_quote! { enum E { A = !1 } },
249		] {
250			assert!(error(&input).starts_with("discriminant must be an integer literal that fits into an `i8`"));
251		}
252	}
253}