larust_macros/lib.rs
1//! Procedural macros for Larust. `#[controller]` lands once it has real
2//! payload (M6) - see `rust-laravel.md`'s milestone plan for why it wasn't
3//! built speculatively.
4
5mod belongs_to_many;
6mod error_view;
7mod form_request;
8mod has_many_through;
9mod model;
10mod observe;
11mod relations;
12mod soft_delete;
13mod view;
14
15use proc_macro::TokenStream;
16use syn::{parse_macro_input, DeriveInput};
17
18/// `#[derive(FormRequest)]`: generates an `axum::extract::FromRequest` impl
19/// that validates a form-urlencoded body against each field's
20/// `#[validate(...)]` rules *before* the handler runs, returning a 422 with
21/// Laravel-shaped field errors on failure (Laravel's `FormRequest`).
22///
23/// ```ignore
24/// #[derive(FormRequest)]
25/// pub struct StorePostRequest {
26/// #[validate(required, length(max = 255))]
27/// pub title: String,
28/// }
29/// ```
30#[proc_macro_derive(FormRequest, attributes(validate))]
31pub fn derive_form_request(input: TokenStream) -> TokenStream {
32 let input = parse_macro_input!(input as DeriveInput);
33 match form_request::expand(input) {
34 Ok(tokens) => tokens.into(),
35 Err(err) => err.to_compile_error().into(),
36 }
37}
38
39/// `view!("posts.index", { posts })`: reads, parses, and resolves
40/// `resources/views/posts/index.blade.xr` (including any `@extends` layout
41/// chain) at compile time, and generates code that renders it into a
42/// `View`. Interpolated expressions (`{{ user.name }}`) and directive
43/// conditions/iterables (`@if(...)`, `@foreach(...)`) are parsed as real
44/// Rust expressions and spliced directly into the generated function body -
45/// an undeclared variable is a genuine `rustc` compile error, not a
46/// custom check.
47///
48/// ```ignore
49/// view!("posts.index", { posts })
50/// ```
51#[proc_macro]
52pub fn view(input: TokenStream) -> TokenStream {
53 let input = parse_macro_input!(input as view::ViewInput);
54 match view::expand(input) {
55 Ok(tokens) => tokens.into(),
56 Err(err) => err.to_compile_error().into(),
57 }
58}
59
60/// `error_view!("404")`: compiles `resources/views/errors/404.blade.xr` if
61/// the app defines one, else Larust's own built-in default page for that
62/// status - always produces a `String`. See `error_view.rs`'s own doc
63/// comment for the override mechanism's limitations (no context bindings,
64/// so no `@wire`/`@can`/`@role`/`persist` globals, and best kept
65/// self-contained rather than `@extends`-ing a session-aware layout).
66///
67/// ```ignore
68/// error_view!("404")
69/// ```
70#[proc_macro]
71pub fn error_view(input: TokenStream) -> TokenStream {
72 let input = parse_macro_input!(input as syn::LitStr);
73 match error_view::expand(&input) {
74 Ok(tokens) => tokens.into(),
75 Err(err) => err.to_compile_error().into(),
76 }
77}
78
79/// `#[derive(Model)]`: generates `TABLE`/field-name constants, `query()`,
80/// `all()`, `find(id)`, `create(data)`, and `delete(id)` over
81/// `larust-orm`'s `QueryBuilder`, plus route model binding - an
82/// `axum::extract::FromRequestParts` impl so a handler can declare
83/// `post: Post` on a route like `/posts/{post}` and have it auto-resolved
84/// (404 if not found). Requires `#[table("...")]` on the struct and
85/// exactly one `#[primary_key]` field (currently must be `i64`).
86/// `#[route_key("slug")]` looks records up by that field instead of the
87/// primary key. `#[timestamps]` (Laravel's `$table->timestamps()`) opts
88/// into automatic `created_at`/`updated_at` population - both must exist
89/// as `i64` (Unix seconds) fields; `create()` stamps both, `update()`
90/// re-stamps `updated_at` only, and neither appears in the generated
91/// `New*` struct, matching Eloquent's own "never set these yourself"
92/// behavior.
93///
94/// `#[soft_deletes]` (Laravel's `SoftDeletes` trait) opts into a nullable
95/// `deleted_at: Option<i64>` field: `delete()` sets it instead of
96/// removing the row, every `query()`/`find()`/`all()`/route-model-binding
97/// lookup transparently excludes trashed rows (`QueryBuilder::{
98/// with_trashed, only_trashed}` opt back in), and `force_delete`/
99/// `restore`/`find_with_trashed`/`.trashed()` round out the rest.
100///
101/// `#[observe(creating = ..., created = ..., updating = ..., updated = ...,
102/// deleting = ..., deleted = ...)]` (Laravel's model-event observers) runs a
103/// plain function around `create`/`update`/`delete` - `creating`/`updating`
104/// transform (or veto, by returning `Err`) the data before the write;
105/// `created`/`updated`/`deleted` run after, with the result; `deleting`
106/// runs before, with the row fetched fresh for the purpose. Fixed hook
107/// signatures, checked by `rustc` at the generated call site - a
108/// mismatch is a compile error pointing at the attribute itself, not a
109/// trait-impl error several layers removed from it.
110///
111/// `#[has_many(...)]`/`#[has_one(...)]`/`#[belongs_to(...)]` (repeatable)
112/// generate Laravel-style relationship accessor methods, both a lazy
113/// per-instance form and a batch/eager `load_*` form; `#[belongs_to_many(
114/// ...)]` (repeatable) generates a many-to-many relationship through a
115/// pivot table (`tags()`/`attach_*`/`detach_*`/`sync_*`, no eager-loading
116/// form yet); `#[has_many_through(...)]` (repeatable) generates a 3-table
117/// relationship (Laravel's `hasManyThrough`) as a composable
118/// `{method}_query()` plus a `{method}()` convenience wrapper, built on
119/// `QueryBuilder::where_in_query` rather than a real `JOIN` (also no
120/// eager-loading form yet) - see `docs/MACROS.md` for the full grammar
121/// and generated shapes.
122///
123/// ```ignore
124/// #[derive(Model, sqlx::FromRow)]
125/// #[table("posts")]
126/// #[belongs_to(User, foreign_key = "user_id")]
127/// #[belongs_to_many(Tag, through = "post_tag", foreign_key = "post_id", related_pivot_key = "tag_id")]
128/// pub struct Post {
129/// #[primary_key]
130/// pub id: i64,
131/// pub user_id: i64,
132/// pub title: String,
133/// }
134/// ```
135#[proc_macro_derive(
136 Model,
137 attributes(
138 table,
139 primary_key,
140 route_key,
141 timestamps,
142 soft_deletes,
143 observe,
144 has_many,
145 has_one,
146 belongs_to,
147 belongs_to_many,
148 has_many_through
149 )
150)]
151pub fn derive_model(input: TokenStream) -> TokenStream {
152 let input = parse_macro_input!(input as DeriveInput);
153 match model::expand(input) {
154 Ok(tokens) => tokens.into(),
155 Err(err) => err.to_compile_error().into(),
156 }
157}