ferro-macros 0.2.22

Procedural macros for Ferro framework
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
//! Procedural macros for the Ferro framework
//!
//! This crate provides compile-time validated macros for:
//! - Inertia.js responses with component validation
//! - Named route redirects with route validation
//! - Service auto-registration
//! - Handler attribute for controller methods
//! - FormRequest for validated request data
//! - Jest-like testing with describe! and test! macros

use proc_macro::TokenStream;

mod describe;
mod domain_error;
mod ferro_test;
mod handler;
mod inertia;
mod injectable;
mod model;
mod redirect;
mod request;
mod resource;
mod service;
mod test_macro;
mod utils;
mod validate;

/// Derive macro for generating `Serialize` implementation for Inertia props
///
/// # Example
///
/// ```rust,ignore
/// #[derive(InertiaProps)]
/// struct HomeProps {
///     title: String,
///     user: User,
/// }
/// ```
#[proc_macro_derive(InertiaProps, attributes(inertia))]
pub fn derive_inertia_props(input: TokenStream) -> TokenStream {
    inertia::derive_inertia_props_impl(input)
}

/// Create an Inertia response with compile-time component validation
///
/// # Examples
///
/// ## With typed struct (recommended for type safety):
/// ```rust,ignore
/// #[derive(InertiaProps)]
/// struct HomeProps {
///     title: String,
///     user: User,
/// }
///
/// inertia_response!("Home", HomeProps { title: "Welcome".into(), user })
/// ```
///
/// ## With JSON-like syntax (for quick prototyping):
/// ```rust,ignore
/// inertia_response!("Dashboard", { "user": { "name": "John" } })
/// ```
///
/// This macro validates that the component file exists at compile time.
/// If `frontend/src/pages/Dashboard.tsx` doesn't exist, you'll get a compile error.
#[proc_macro]
pub fn inertia_response(input: TokenStream) -> TokenStream {
    inertia::inertia_response_impl(input)
}

/// Create a redirect to a path or named route
///
/// # Examples
///
/// ```rust,ignore
/// // Path redirect (starts with /)
/// redirect!("/dashboard").into()
///
/// // Named route redirect
/// redirect!("users.index").into()
///
/// // Redirect with route parameters
/// redirect!("users.show").with("id", "42").into()
///
/// // Redirect with query parameters
/// redirect!("users.index").query("page", "1").into()
/// ```
///
/// For named routes, this macro validates that the route exists at compile time.
/// Path redirects (starting with `/`) bypass validation and redirect directly.
#[proc_macro]
pub fn redirect(input: TokenStream) -> TokenStream {
    redirect::redirect_impl(input)
}

/// Mark a trait as a service for the App container
///
/// This attribute macro automatically adds `Send + Sync + 'static` bounds
/// to your trait, making it suitable for use with the dependency injection
/// container.
///
/// # Example
///
/// ```rust,ignore
/// use ferro::service;
///
/// #[service]
/// pub trait HttpClient {
///     async fn get(&self, url: &str) -> Result<String, Error>;
/// }
///
/// // This expands to:
/// pub trait HttpClient: Send + Sync + 'static {
///     async fn get(&self, url: &str) -> Result<String, Error>;
/// }
/// ```
///
/// Then you can use it with the App container:
///
/// ```rust,ignore
/// // Register
/// App::bind::<dyn HttpClient>(Arc::new(RealHttpClient::new()));
///
/// // Resolve
/// let client: Arc<dyn HttpClient> = App::make::<dyn HttpClient>().unwrap();
/// ```
#[proc_macro_attribute]
pub fn service(attr: TokenStream, input: TokenStream) -> TokenStream {
    service::service_impl(attr, input)
}

/// Attribute macro to auto-register a concrete type as a singleton
///
/// This macro automatically:
/// 1. Derives `Default` and `Clone` for the struct
/// 2. Registers it as a singleton in the App container at startup
///
/// # Example
///
/// ```rust,ignore
/// use ferro::injectable;
///
/// #[injectable]
/// pub struct AppState {
///     pub counter: u32,
/// }
///
/// // Automatically registered at startup
/// // Resolve via:
/// let state: AppState = App::get().unwrap();
/// ```
#[proc_macro_attribute]
pub fn injectable(_attr: TokenStream, input: TokenStream) -> TokenStream {
    injectable::injectable_impl(input)
}

/// Define a domain error with automatic HTTP response conversion
///
/// This macro automatically:
/// 1. Derives `Debug` and `Clone` for the type
/// 2. Implements `Display`, `Error`, and `HttpError` traits
/// 3. Implements `From<T> for FrameworkError` for seamless `?` usage
///
/// # Attributes
///
/// - `status`: HTTP status code (default: 500)
/// - `message`: Error message for Display (default: struct name converted to sentence)
///
/// # Example
///
/// ```rust,ignore
/// use ferro::domain_error;
///
/// #[domain_error(status = 404, message = "User not found")]
/// pub struct UserNotFoundError {
///     pub user_id: i32,
/// }
///
/// // Usage in controller - just use ? operator
/// pub async fn get_user(id: i32) -> Result<User, FrameworkError> {
///     users.find(id).ok_or(UserNotFoundError { user_id: id })?
/// }
/// ```
#[proc_macro_attribute]
pub fn domain_error(attr: TokenStream, input: TokenStream) -> TokenStream {
    domain_error::domain_error_impl(attr, input)
}

/// Attribute macro for controller handler methods
///
/// Transforms handler functions to automatically extract typed parameters
/// from HTTP requests using the `FromRequest` trait.
///
/// # Examples
///
/// ## With Request parameter:
/// ```rust,ignore
/// use ferro::{handler, Request, Response, json_response};
///
/// #[handler]
/// pub async fn index(req: Request) -> Response {
///     json_response!({ "message": "Hello" })
/// }
/// ```
///
/// ## With FormRequest parameter:
/// ```rust,ignore
/// use ferro::{handler, Response, json_response, request};
///
/// #[request]
/// pub struct CreateUserRequest {
///     #[validate(email)]
///     pub email: String,
/// }
///
/// #[handler]
/// pub async fn store(form: CreateUserRequest) -> Response {
///     // `form` is already validated - returns 422 if invalid
///     json_response!({ "email": form.email })
/// }
/// ```
///
/// ## Without parameters:
/// ```rust,ignore
/// #[handler]
/// pub async fn health_check() -> Response {
///     json_response!({ "status": "ok" })
/// }
/// ```
#[proc_macro_attribute]
pub fn handler(attr: TokenStream, input: TokenStream) -> TokenStream {
    handler::handler_impl(attr, input)
}

/// Derive macro for FormRequest trait
///
/// Generates the `FormRequest` trait implementation for a struct.
/// The struct must also derive `serde::Deserialize` and `validator::Validate`.
///
/// For the cleanest DX, use the `#[request]` attribute macro instead,
/// which handles all derives automatically.
///
/// # Example
///
/// ```rust,ignore
/// use ferro::{FormRequest, Deserialize, Validate};
///
/// #[derive(Deserialize, Validate, FormRequest)]
/// pub struct CreateUserRequest {
///     #[validate(email)]
///     pub email: String,
///
///     #[validate(length(min = 8))]
///     pub password: String,
/// }
/// ```
#[proc_macro_derive(FormRequest)]
pub fn derive_form_request(input: TokenStream) -> TokenStream {
    request::derive_request_impl(input)
}

/// Attribute macro for clean request data definition
///
/// This is the recommended way to define validated request types.
/// It automatically adds the necessary derives and generates the trait impl.
///
/// Works with both:
/// - `application/json` - JSON request bodies
/// - `application/x-www-form-urlencoded` - HTML form submissions
///
/// # Example
///
/// ```rust,ignore
/// use ferro::request;
///
/// #[request]
/// pub struct CreateUserRequest {
///     #[validate(email)]
///     pub email: String,
///
///     #[validate(length(min = 8))]
///     pub password: String,
/// }
///
/// // This can now be used directly in handlers:
/// #[handler]
/// pub async fn store(form: CreateUserRequest) -> Response {
///     // Automatically validated - returns 422 with errors if invalid
///     json_response!({ "email": form.email })
/// }
/// ```
#[proc_macro_attribute]
pub fn request(attr: TokenStream, input: TokenStream) -> TokenStream {
    request::request_attr_impl(attr, input)
}

/// Attribute macro for database-enabled tests
///
/// This macro simplifies writing tests that need database access by automatically
/// setting up an in-memory SQLite database with migrations applied.
///
/// By default, it uses `crate::migrations::Migrator` as the migrator type,
/// following Ferro's convention for migration location.
///
/// # Examples
///
/// ## Basic usage (recommended):
/// ```rust,ignore
/// use ferro::ferro_test;
/// use ferro::testing::TestDatabase;
///
/// #[ferro_test]
/// async fn test_user_creation(db: TestDatabase) {
///     // db is an in-memory SQLite database with all migrations applied
///     // Any code using DB::connection() will use this test database
///     let action = CreateUserAction::new();
///     let user = action.execute("test@example.com").await.unwrap();
///     assert!(user.id > 0);
/// }
/// ```
///
/// ## Without TestDatabase parameter:
/// ```rust,ignore
/// #[ferro_test]
/// async fn test_action_without_direct_db_access() {
///     // Database is set up but not directly accessed
///     // Actions using DB::connection() still work
///     let action = MyAction::new();
///     action.execute().await.unwrap();
/// }
/// ```
///
/// ## With custom migrator:
/// ```rust,ignore
/// #[ferro_test(migrator = my_crate::CustomMigrator)]
/// async fn test_with_custom_migrator(db: TestDatabase) {
///     // Uses custom migrator instead of default
/// }
/// ```
#[proc_macro_attribute]
pub fn ferro_test(attr: TokenStream, input: TokenStream) -> TokenStream {
    ferro_test::ferro_test_impl(attr, input)
}

/// Group related tests with a descriptive name
///
/// Creates a module containing related tests, similar to Jest's describe blocks.
/// Supports nesting for hierarchical test organization.
///
/// # Example
///
/// ```rust,ignore
/// use ferro::{describe, test, expect};
/// use ferro::testing::TestDatabase;
///
/// describe!("ListTodosAction", {
///     test!("returns empty list when no todos exist", async fn(db: TestDatabase) {
///         let action = ListTodosAction::new();
///         let todos = action.execute().await.unwrap();
///         expect!(todos).to_be_empty();
///     });
///
///     // Nested describe for grouping related tests
///     describe!("with pagination", {
///         test!("returns first page", async fn(db: TestDatabase) {
///             // ...
///         });
///     });
/// });
/// ```
#[proc_macro]
pub fn describe(input: TokenStream) -> TokenStream {
    describe::describe_impl(input)
}

/// Define an individual test case with a descriptive name
///
/// Creates a test function with optional TestDatabase parameter.
/// The test name is displayed in failure output for easy identification.
///
/// # Examples
///
/// ## Async test with database
/// ```rust,ignore
/// test!("creates a user", async fn(db: TestDatabase) {
///     let user = CreateUserAction::new().execute("test@example.com").await.unwrap();
///     expect!(user.email).to_equal("test@example.com".to_string());
/// });
/// ```
///
/// ## Async test without database
/// ```rust,ignore
/// test!("calculates sum", async fn() {
///     let result = calculate_sum(1, 2).await;
///     expect!(result).to_equal(3);
/// });
/// ```
///
/// ## Sync test
/// ```rust,ignore
/// test!("adds numbers", fn() {
///     expect!(1 + 1).to_equal(2);
/// });
/// ```
///
/// On failure, the test name is shown:
/// ```text
/// Test: "creates a user"
///   at src/actions/user_action.rs:25
///
///   expect!(actual).to_equal(expected)
///
///   Expected: "test@example.com"
///   Received: "wrong@email.com"
/// ```
#[proc_macro]
pub fn test(input: TokenStream) -> TokenStream {
    test_macro::test_impl(input)
}

/// Derive macro for reducing SeaORM model boilerplate
///
/// Generates create builder, update builder, and convenience methods for Ferro models.
/// Apply to a SeaORM Model struct to get:
/// - `Model::query()` - Start a new QueryBuilder
/// - `Model::create()` - Get a builder for inserting new records
/// - `model.update()` - Get an UpdateBuilder for selective field updates
/// - `model.delete()` - Delete the record
///
/// # Example
///
/// ```rust,ignore
/// use ferro::FerroModel;
/// use sea_orm::entity::prelude::*;
///
/// #[derive(Clone, Debug, DeriveEntityModel, FerroModel)]
/// #[sea_orm(table_name = "users")]
/// pub struct Model {
///     #[sea_orm(primary_key)]
///     pub id: i32,
///     pub name: String,
///     pub email: String,
///     pub bio: Option<String>,
/// }
///
/// // Create a new record
/// let user = User::create()
///     .set_name("John")
///     .set_email("john@example.com")
///     .insert()
///     .await?;
///
/// // Update specific fields only (unchanged fields are not sent to DB)
/// let updated = user
///     .update()
///     .set_name("John Doe")
///     .set_bio("Developer")
///     .save()
///     .await?;
///
/// // Clear an optional field to NULL
/// let updated = updated
///     .update()
///     .clear_bio()
///     .save()
///     .await?;
///
/// // Query records
/// let users = User::query()
///     .filter(Column::Name.contains("John"))
///     .all()
///     .await?;
/// ```
#[proc_macro_derive(FerroModel)]
pub fn derive_ferro_model(input: TokenStream) -> TokenStream {
    model::ferro_model_impl(input)
}

/// Derive macro for declarative struct validation using Ferro's rules
///
/// Generates `Validatable` trait implementation from field attributes.
/// Validation rules are co-located with the struct definition.
///
/// This uses Ferro's Laravel-style validation rules (required(), email(), etc.)
/// rather than the external `validator` crate.
///
/// # Example
///
/// ```rust,ignore
/// use ferro::ValidateRules;
///
/// #[derive(ValidateRules)]
/// struct CreateUserRequest {
///     #[rule(required, email)]
///     email: String,
///
///     #[rule(required, min(8))]
///     password: String,
///
///     #[rule(required, integer, min(18))]
///     age: Option<i32>,
/// }
///
/// // Usage
/// let request = CreateUserRequest { ... };
/// request.validate()?;
/// ```
#[proc_macro_derive(ValidateRules, attributes(rule))]
pub fn derive_validate_rules(input: TokenStream) -> TokenStream {
    validate::validate_impl(input)
}

/// Derive macro for generating `Resource` trait implementation from struct annotations
///
/// Supports struct-level and field-level `#[resource(...)]` attributes:
///
/// - `#[resource(model = "path::to::Model")]` (struct-level) — generates `From<Model>` impl
/// - `#[resource(rename = "new_name")]` (field-level) — use a different key in JSON output
/// - `#[resource(skip)]` (field-level) — exclude field from JSON output
///
/// # Example
///
/// ```rust,ignore
/// use ferro::ApiResource;
///
/// #[derive(ApiResource)]
/// #[resource(model = "entities::users::Model")]
/// pub struct UserResource {
///     pub id: i32,
///     pub name: String,
///     #[resource(rename = "member_since")]
///     pub created_at: String,
///     #[resource(skip)]
///     pub password_hash: String,
/// }
/// ```
#[proc_macro_derive(ApiResource, attributes(resource))]
pub fn derive_api_resource(input: TokenStream) -> TokenStream {
    resource::api_resource_impl(input)
}