tinyscript-derive 0.4.0

Procedural macros for tinyscript
Documentation
// Copyright © 2025 Stephan Kunz
//! Derive macro [`ScriptEnum`].

#[doc(hidden)]
extern crate proc_macro;

#[doc(hidden)]
extern crate alloc;

use proc_macro2::TokenStream;
use quote::quote;
use syn::{DeriveInput, Expr, ExprLit, ExprUnary, Fields, Lit, LitInt, UnOp};

/// The error for a discriminant that is no integer literal fitting into an `i8`.
fn discriminant_error(expr: &Expr) -> syn::Error {
	syn::Error::new_spanned(
		expr,
		"discriminant must be an integer literal that fits into an `i8`, e.g. `5` or `-3`; \
		 constants and computations are not supported",
	)
}

/// The value of an explicit discriminant: an integer literal, optionally negated.
fn explicit_discriminant(expr: &Expr) -> syn::Result<i8> {
	let parse = |literal: &LitInt, negative: bool| {
		let digits = literal.base10_digits();
		// parse with the sign, so that `-128` fits
		let text = if negative { format!("-{digits}") } else { digits.to_owned() };
		text.parse::<i8>()
			.map_err(|_| discriminant_error(expr))
	};
	match expr {
		Expr::Lit(ExprLit {
			lit: Lit::Int(literal), ..
		}) => parse(literal, false),
		Expr::Unary(ExprUnary {
			op: UnOp::Neg(_),
			expr: operand,
			..
		}) => match &**operand {
			Expr::Lit(ExprLit {
				lit: Lit::Int(literal), ..
			}) => parse(literal, true),
			_ => Err(discriminant_error(expr)),
		},
		_ => Err(discriminant_error(expr)),
	}
}

/// Implementation of the derive macro [`ScriptEnum`]
fn derive_scripting_enum(input: &DeriveInput) -> syn::Result<TokenStream> {
	// structure name
	let ident = &input.ident;

	let data = match &input.data {
		syn::Data::Enum(data) => data,
		syn::Data::Struct(data) => {
			return Err(syn::Error::new_spanned(
				data.struct_token,
				"`ScriptEnum` supports only enums, not structs",
			));
		}
		syn::Data::Union(data) => {
			return Err(syn::Error::new_spanned(
				data.union_token,
				"`ScriptEnum` supports only enums, not unions",
			));
		}
	};

	// the variants are numbered like Rust does: from 0, or continuing from an explicit discriminant;
	// `None` once the next implicit discriminant would exceed `i8::MAX`
	let mut next = Some(0_i8);
	let mut variant_keys = Vec::new();
	let mut variant_discriminants = Vec::new();
	for variant in &data.variants {
		if !matches!(variant.fields, Fields::Unit) {
			return Err(syn::Error::new_spanned(
				&variant.fields,
				"`ScriptEnum` variants must not have fields",
			));
		}
		let discriminant = match &variant.discriminant {
			Some((_eq, expr)) => explicit_discriminant(expr)?,
			None => next.ok_or_else(|| {
				syn::Error::new_spanned(&variant.ident, "the implicit discriminant of this variant exceeds `i8::MAX`")
			})?,
		};
		next = discriminant.checked_add(1);
		variant_keys.push(variant.ident.to_string());
		variant_discriminants.push(discriminant);
	}

	//
	let (impl_generics, type_generics, where_clause) = input.generics.split_for_impl();

	let derived: TokenStream = "#[automatically_derived]"
		.parse()
		.expect("derive(ScriptEnum) - derived");
	let diagnostic: TokenStream = "#[diagnostic::do_not_recommend]"
		.parse()
		.expect("derive(ScriptEnum) - diagnostic");

	Ok(quote! {
		#derived
		#diagnostic
		impl #impl_generics tinyscript::ScriptEnum for #ident #type_generics #where_clause {
			fn key_value_tuples<'a>() -> tinyscript::__private::Vec<(&'a str, i8)> {
				tinyscript::__private::vec![#((#variant_keys, #variant_discriminants)),*]
			}
		}
	})
}

/// Derive macro [`ScriptEnum`].
/// Enables a Rust enum to be used in a 'C' like mannner within the `tinyscript` language.
///
/// The variants are numbered like Rust does: from 0, or continuing from an explicit discriminant.
/// Explicit discriminants must be integer literals that fit into an `i8`, negative ones included,
/// e.g. `-3`; the variants must have no fields.
///
/// # Usage
/// ```no_test
/// #[derive(ScriptEnum)]
/// enum Color {
///     Red,
///     Green = 5,
///     Blue,
/// }
///
/// // make the variants known to the scripts
/// for (name, discriminant) in Color::key_value_tuples() {
///     runtime.register_enum_tuple(name, discriminant)?;
/// }
/// ```
///
/// # Result
/// Expands the above enum to
/// ```no_test
/// enum Color {
///     Red,
///     Green = 5,
///     Blue,
/// }
///
/// #[automatically_derived]
/// #[diagnostic::do_not_recommend]
/// impl tinyscript::ScriptEnum for Color {
///     fn key_value_tuples<'a>() -> tinyscript::__private::Vec<(&'a str, i8)> {
///         tinyscript::__private::vec![("Red", 0), ("Green", 5), ("Blue", 6)]
///     }
/// }
/// ```
///
/// # Errors
/// Compilation errors, pointing at the cause:
/// - if used on structs or unions
/// - if a variant has fields
/// - if a discriminant is not an integer literal or does not fit into an `i8`
/// - if an implicit discriminant would exceed `i8::MAX`
#[proc_macro_derive(ScriptEnum)]
pub fn derive_script_enum(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
	// Construct a representation of Rust code as a syntax tree
	let input = syn::parse_macro_input!(input as DeriveInput);

	derive_scripting_enum(&input)
		.unwrap_or_else(syn::Error::into_compile_error)
		.into()
}

#[cfg(test)]
mod tests {
	use super::*;
	use syn::parse_quote;

	fn expand(input: &DeriveInput) -> String {
		derive_scripting_enum(input).unwrap().to_string()
	}

	fn error(input: &DeriveInput) -> String {
		derive_scripting_enum(input)
			.unwrap_err()
			.to_string()
	}

	#[test]
	fn variants_are_numbered_from_zero_or_explicit_discriminants() {
		let input: DeriveInput = parse_quote! {
			enum Color { Red, Green = 5, Blue }
		};
		let expanded = expand(&input);
		assert!(expanded.contains("impl tinyscript :: ScriptEnum for Color"));
		assert!(expanded.contains(r#"("Red" , 0i8) , ("Green" , 5i8) , ("Blue" , 6i8)"#));
	}

	#[test]
	fn negative_discriminants_and_the_limits_of_i8() {
		let input: DeriveInput = parse_quote! {
			enum E { A = -128, B, C = -1, D, E = 126, F }
		};
		assert!(
			expand(&input).contains(
				r#"("A" , - 128i8) , ("B" , - 127i8) , ("C" , - 1i8) , ("D" , 0i8) , ("E" , 126i8) , ("F" , 127i8)"#
			)
		);
	}

	#[test]
	fn generics_are_kept() {
		let input: DeriveInput = parse_quote! {
			enum Wrapper<T: Clone> where T: Copy { A }
		};
		assert!(expand(&input).contains("impl < T : Clone > tinyscript :: ScriptEnum for Wrapper < T > where T : Copy"));
	}

	#[test]
	fn structs_and_unions_are_rejected() {
		let input: DeriveInput = parse_quote! { struct S; };
		assert_eq!(error(&input), "`ScriptEnum` supports only enums, not structs");
		let input: DeriveInput = parse_quote! { union U { a: u8 } };
		assert_eq!(error(&input), "`ScriptEnum` supports only enums, not unions");
	}

	#[test]
	fn variants_with_fields_are_rejected() {
		for input in [
			parse_quote! { enum E { A(u8) } },
			parse_quote! { enum E { A, B { x: u8 } } },
		] {
			assert_eq!(error(&input), "`ScriptEnum` variants must not have fields");
		}
	}

	#[test]
	fn implicit_discriminant_beyond_i8_is_rejected() {
		let input: DeriveInput = parse_quote! { enum E { A = 127, B } };
		assert_eq!(error(&input), "the implicit discriminant of this variant exceeds `i8::MAX`");
	}

	#[test]
	fn invalid_explicit_discriminants_are_rejected() {
		for input in [
			parse_quote! { enum E { A = 128 } },
			parse_quote! { enum E { A = -129 } },
			parse_quote! { enum E { A = 'a' } },
			parse_quote! { enum E { A = 1 + 1 } },
			parse_quote! { enum E { A = -X } },
			parse_quote! { enum E { A = !1 } },
		] {
			assert!(error(&input).starts_with("discriminant must be an integer literal that fits into an `i8`"));
		}
	}
}