Skip to main content

alien_macros/
lib.rs

1mod alien_resource;
2
3use proc_macro::TokenStream;
4use quote::quote;
5use syn::{parse_macro_input, Expr, ItemFn};
6
7/// A procedural macro that wraps a function with an AlienEvent scope.
8///
9/// This macro is similar to tracing's `#[instrument]` but for the Alien events system.
10/// It automatically wraps the function body with `AlienEvent::in_scope()`.
11///
12/// # Usage
13///
14/// ```rust,ignore
15/// use alien_macros::alien_event;
16/// use alien_core::{AlienEvent, Result};
17///
18/// #[alien_event(AlienEvent::BuildingStack { stack: "my-stack".to_string() })]
19/// async fn build_stack() -> Result<()> {
20///     // Function body - all events emitted here will be children
21///     // of the BuildingStack event
22///     Ok(())
23/// }
24/// ```
25///
26/// The macro supports any AlienEvent variant:
27///
28/// ```rust,ignore
29/// #[alien_event(AlienEvent::BuildingImage { image: "api:latest".to_string() })]
30/// async fn build_image() -> Result<()> {
31///     Ok(())
32/// }
33/// ```
34///
35/// You can also use expressions for dynamic values:
36///
37/// ```rust,ignore
38/// #[alien_event(AlienEvent::BuildingStack { stack: format!("stack-{}", id) })]
39/// async fn build_dynamic_stack(id: u32) -> Result<()> {
40///     Ok(())
41/// }
42/// ```
43///
44/// The macro only works with async functions since it uses `AlienEvent::in_scope()` internally.
45#[proc_macro_attribute]
46pub fn alien_event(args: TokenStream, input: TokenStream) -> TokenStream {
47    let event_expr = parse_macro_input!(args as Expr);
48    let input_fn = parse_macro_input!(input as ItemFn);
49
50    let fn_vis = &input_fn.vis;
51    let fn_sig = &input_fn.sig;
52    let fn_block = &input_fn.block;
53    let fn_attrs = &input_fn.attrs;
54
55    // Check if function is async
56    let is_async = fn_sig.asyncness.is_some();
57
58    if is_async {
59        // For async functions, use in_scope for automatic success/failure tracking
60        let expanded = quote! {
61            #(#fn_attrs)*
62            #fn_vis #fn_sig {
63                (#event_expr).in_scope(|_event_handle| async move #fn_block).await
64            }
65        };
66        TokenStream::from(expanded)
67    } else {
68        // For sync functions, we can't use in_scope since it's async
69        // Instead, we'll just note that this macro is designed for async functions
70        panic!("alien_event macro currently only supports async functions. Use AlienEvent::emit() manually for sync functions.");
71    }
72}
73
74mod controller;
75
76use controller::{controller_impl, controller_struct};
77
78/// Macro for simplifying resource controller implementations.
79///
80/// When applied to a struct, it adds internal state management fields.
81/// When applied to an impl block, it generates the ResourceController trait implementation.
82///
83/// # Usage on struct:
84/// ```rust,ignore
85/// #[controller]
86/// struct AwsFunctionController {
87///     pub arn: Option<String>,
88///     pub url: Option<String>,
89/// }
90/// ```
91///
92/// # Usage on impl:
93/// ```rust,ignore
94/// #[controller]
95/// impl AwsFunctionController {
96///     #[flow_entry(Create)]
97///     #[handler(state = CreateStart, on_failure = CreateFailed, status = ResourceStatus::Provisioning)]
98///     async fn create_start(&mut self, ctx: &ResourceControllerContext) -> Result<HandlerAction> {
99///         // ...
100///     }
101/// }
102/// ```
103#[proc_macro_attribute]
104pub fn controller(args: TokenStream, input: TokenStream) -> TokenStream {
105    // Check if this is a struct or impl block
106    if syn::parse::<syn::ItemStruct>(input.clone()).is_ok() {
107        return controller_struct(args, input);
108    }
109
110    if syn::parse::<syn::ItemImpl>(input.clone()).is_ok() {
111        return controller_impl(args, input);
112    }
113
114    panic!("controller macro can only be applied to structs or impl blocks");
115}
116
117/// Helper attributes for the controller macro
118#[proc_macro_attribute]
119pub fn flow_entry(_args: TokenStream, input: TokenStream) -> TokenStream {
120    // This is just a marker attribute, return input unchanged
121    input
122}
123
124#[proc_macro_attribute]
125pub fn handler(_args: TokenStream, input: TokenStream) -> TokenStream {
126    // This is just a marker attribute, return input unchanged
127    input
128}
129
130/// Macro for defining terminal states in a controller
131#[proc_macro]
132pub fn terminal_state(_input: TokenStream) -> TokenStream {
133    // This will be used inside the controller impl
134    // For now, just return an empty token stream as it will be handled by the controller macro
135    quote::quote! {}.into()
136}
137
138/// Makes a struct an extension's resource type:
139/// `#[alien_resource(type = "acme/dns-zone", outputs = DnsZoneOutputs, lifecycles = [Frozen, Live], holds_data = false)]`.
140///
141/// It writes the type's `RESOURCE_TYPE`, `ResourceDefinition` for the struct (which needs an
142/// `id: String` field), `ResourceOutputsDefinition` for its outputs, and the extension SDK's
143/// `AlienResource`, whose consts the type's descriptor is built from. The expansion names
144/// `alien_extension_sdk`, so it is for an extension's types crate.
145#[proc_macro_attribute]
146pub fn alien_resource(args: TokenStream, input: TokenStream) -> TokenStream {
147    alien_resource::expand(args.into(), input.into())
148        .unwrap_or_else(syn::Error::into_compile_error)
149        .into()
150}