Skip to main content

glacier_macros/
lib.rs

1//! Procedural macros for Glacier. Use them through the `glacier` crate.
2
3mod app;
4mod controller;
5mod controllers;
6mod embed;
7mod enumeration;
8mod model;
9mod model_attr;
10mod models;
11mod openapi;
12mod paths;
13mod render;
14mod routes;
15mod scopes;
16mod template;
17mod test;
18mod tests;
19mod views;
20
21use proc_macro::TokenStream;
22use quote::quote;
23use syn::{DeriveInput, ItemFn, LitStr, parse_macro_input};
24
25/// Derives `glacier::Model`. See the trait docs for details.
26#[proc_macro_derive(Model, attributes(glacier, validate))]
27pub fn derive_model(input: TokenStream) -> TokenStream {
28    let input = parse_macro_input!(input as DeriveInput);
29    model::expand(input)
30        .unwrap_or_else(syn::Error::into_compile_error)
31        .into()
32}
33
34/// Field validations on a changeset, in the `#[validate(…)]` syntax; see
35/// `glacier::validate!`.
36#[proc_macro]
37pub fn validate(input: TokenStream) -> TokenStream {
38    use syn::parse::Parser;
39    let parser = |input: syn::parse::ParseStream| -> syn::Result<proc_macro2::TokenStream> {
40        let changeset: syn::Expr = input.parse()?;
41        input.parse::<syn::Token![,]>()?;
42        let field: syn::Ident = input.parse()?;
43        input.parse::<syn::Token![,]>()?;
44        let mut rules = Vec::new();
45        let rules_parser = syn::meta::parser(|meta| {
46            rules.push(model::validation(&field, &meta)?);
47            Ok(())
48        });
49        rules_parser.parse2(input.parse()?)?;
50        Ok(quote! { (#changeset) #(#rules)* })
51    };
52    parser
53        .parse(input)
54        .unwrap_or_else(syn::Error::into_compile_error)
55        .into()
56}
57
58/// Derives `glacier::view::Template`; see `glacier::view` for the syntax.
59#[proc_macro_derive(Template, attributes(template))]
60pub fn derive_template(input: TokenStream) -> TokenStream {
61    let input = parse_macro_input!(input as DeriveInput);
62    template::expand_derive(input)
63        .unwrap_or_else(syn::Error::into_compile_error)
64        .into()
65}
66
67/// An inline template, evaluated in place to a `glacier::view::Rendered`.
68/// Local variables are in scope.
69#[proc_macro]
70pub fn html(input: TokenStream) -> TokenStream {
71    let literal = parse_macro_input!(input as LitStr);
72    template::expand_html(literal)
73        .unwrap_or_else(syn::Error::into_compile_error)
74        .into()
75}
76
77/// Renders a template in the app layout; see `glacier::view::render`.
78#[proc_macro]
79pub fn render(input: TokenStream) -> TokenStream {
80    let render = parse_macro_input!(input as render::Render);
81    render::expand(render)
82        .unwrap_or_else(syn::Error::into_compile_error)
83        .into()
84}
85
86/// Makes a struct a model: adds `id` and timestamps, makes fields `pub`,
87/// and derives `Debug`, `Clone`, `Serialize` and `Model`.
88#[proc_macro_attribute]
89pub fn model(args: TokenStream, item: TokenStream) -> TokenStream {
90    let item = parse_macro_input!(item as syn::ItemStruct);
91    model_attr::expand(args.into(), item)
92        .unwrap_or_else(syn::Error::into_compile_error)
93        .into()
94}
95
96/// Declares the app's controller modules, from `.glacier` or `.rs` files.
97#[proc_macro]
98pub fn controllers(input: TokenStream) -> TokenStream {
99    let parser = controllers::Names::parse_terminated;
100    let names = parse_macro_input!(input with parser);
101    controllers::expand(names)
102        .unwrap_or_else(syn::Error::into_compile_error)
103        .into()
104}
105
106/// Turns an `impl` block into a controller; see `glacier::controller`.
107#[proc_macro_attribute]
108pub fn controller(args: TokenStream, item: TokenStream) -> TokenStream {
109    let item = parse_macro_input!(item as syn::ItemImpl);
110    controller::expand(args.into(), item)
111        .unwrap_or_else(syn::Error::into_compile_error)
112        .into()
113}
114
115/// Generates a struct per template in `src/views/`; see `glacier::view`.
116#[proc_macro]
117pub fn views(input: TokenStream) -> TokenStream {
118    views::expand(input.into())
119        .unwrap_or_else(syn::Error::into_compile_error)
120        .into()
121}
122
123/// The route table; see `glacier::routes!`.
124#[proc_macro]
125pub fn routes(input: TokenStream) -> TokenStream {
126    let routes = parse_macro_input!(input as routes::Routes);
127    routes::expand(routes)
128        .unwrap_or_else(syn::Error::into_compile_error)
129        .into()
130}
131
132/// Route pattern constants and path helpers; see `glacier::paths!`.
133#[proc_macro]
134pub fn paths(input: TokenStream) -> TokenStream {
135    let paths = parse_macro_input!(input as paths::Paths);
136    paths::expand(paths)
137        .unwrap_or_else(syn::Error::into_compile_error)
138        .into()
139}
140
141/// Named, chainable queries on a model: each `fn name(query: Query<M>, …)
142/// -> Query<M>` becomes `M::name(…)` and a method on `Query<M>` (through an
143/// `MScopes` trait), so `Post::published().recent()` chains.
144#[proc_macro_attribute]
145pub fn scopes(args: TokenStream, item: TokenStream) -> TokenStream {
146    if !args.is_empty() {
147        return syn::Error::new(
148            proc_macro2::Span::call_site(),
149            "#[scopes] takes no arguments",
150        )
151        .into_compile_error()
152        .into();
153    }
154    let item = parse_macro_input!(item as syn::ItemImpl);
155    scopes::expand(item)
156        .unwrap_or_else(syn::Error::into_compile_error)
157        .into()
158}
159
160/// An enum stored as text in a column (`"draft"`), with predicates
161/// (`is_draft()`), parsing and form casting. See `glacier::db`.
162#[proc_macro_attribute]
163pub fn enumeration(args: TokenStream, item: TokenStream) -> TokenStream {
164    if !args.is_empty() {
165        return syn::Error::new(
166            proc_macro2::Span::call_site(),
167            "#[enumeration] takes no arguments",
168        )
169        .into_compile_error()
170        .into();
171    }
172    let item = parse_macro_input!(item as syn::ItemEnum);
173    enumeration::expand(item)
174        .unwrap_or_else(syn::Error::into_compile_error)
175        .into()
176}
177
178/// `models!(post, comment)`: declares an app's model modules, from
179/// `src/models/<name>.glacier` (compiled into `.glacier/models/`) or
180/// `<name>.rs`, re-exporting what each defines.
181/// `glacier::app!()`: all of an app's `src/lib.rs`. Declares every
182/// folder and file under `src/` (no `mod.rs` lists: a folder's files are
183/// re-exported from it, `src/jobs/` gets `jobs::all()`), the migrations in
184/// `db/migrations/` and `db/<name>/migrations/`, and `app(config, repo)`:
185/// the config and database, migrations, seeds and jobs, then
186/// `src/app.glacier`'s settings, `public/`'s static files and the routes.
187#[proc_macro]
188pub fn app(input: TokenStream) -> TokenStream {
189    if !input.is_empty() {
190        return syn::Error::new(proc_macro2::Span::call_site(), "app!() takes nothing")
191            .into_compile_error()
192            .into();
193    }
194    app::app()
195        .unwrap_or_else(syn::Error::into_compile_error)
196        .into()
197}
198
199/// `glacier::serve!()`: all of an app's `src/main.rs`, serving `app()`
200/// with the config in `config/` (or running a command, `app migrate`).
201#[proc_macro]
202pub fn serve(input: TokenStream) -> TokenStream {
203    if !input.is_empty() {
204        return syn::Error::new(proc_macro2::Span::call_site(), "serve!() takes nothing")
205            .into_compile_error()
206            .into();
207    }
208    app::serve()
209        .unwrap_or_else(syn::Error::into_compile_error)
210        .into()
211}
212
213#[proc_macro]
214pub fn models(input: TokenStream) -> TokenStream {
215    let names = parse_macro_input!(input with controllers::Names::parse_terminated);
216    models::expand(names, "model")
217        .unwrap_or_else(syn::Error::into_compile_error)
218        .into()
219}
220
221/// `jobs!(send_report)`: declares an app's background job modules (from
222/// `src/jobs/<name>.rs`), re-exports each job, and generates `all()`, the
223/// `Jobs` registering every one (`SendReport` for `send_report`), for
224/// `App::jobs(jobs::all())`.
225#[proc_macro]
226pub fn jobs(input: TokenStream) -> TokenStream {
227    let names = parse_macro_input!(input with controllers::Names::parse_terminated);
228    let types: Vec<_> = names
229        .iter()
230        .map(|name| {
231            quote::format_ident!(
232                "{}",
233                glacier_inflect::pascal_case(&name.to_string()),
234                span = name.span()
235            )
236        })
237        .collect();
238    match models::expand(names, "job") {
239        Ok(modules) => quote::quote! {
240            #modules
241
242            /// Every job the app runs: pass to `App::jobs`.
243            pub fn all() -> ::glacier::jobs::Jobs {
244                ::glacier::jobs::Jobs::new() #(.register::<#types>())*
245            }
246        }
247        .into(),
248        Err(err) => err.into_compile_error().into(),
249    }
250}
251
252/// `seeds!()`: declares the app's `seeds` module, from `src/seeds.glacier`
253/// or `src/seeds.rs`; see `App::seeds`.
254#[proc_macro]
255pub fn seeds(input: TokenStream) -> TokenStream {
256    if !input.is_empty() {
257        return syn::Error::new(
258            proc_macro2::Span::call_site(),
259            "seeds!() takes no arguments",
260        )
261        .into_compile_error()
262        .into();
263    }
264    models::seeds()
265        .unwrap_or_else(syn::Error::into_compile_error)
266        .into()
267}
268
269/// `services!(report_detail)`: declares an app's service modules (plain
270/// objects for code that belongs to no one model), from
271/// `src/services/<name>.glacier` or `<name>.rs`.
272#[proc_macro]
273pub fn services(input: TokenStream) -> TokenStream {
274    let names = parse_macro_input!(input with controllers::Names::parse_terminated);
275    models::expand(names, "service")
276        .unwrap_or_else(syn::Error::into_compile_error)
277        .into()
278}
279
280/// `migrations!()` in `src/lib.rs`: the app's migrations, every
281/// `m<version>_<name>.glacier` (or `.rs`) in `db/migrations/`, oldest
282/// first, as `pub mod migrations` with `all()` for `App::migrations`.
283/// `migrations!(analytics)`: a named database's, from
284/// `db/analytics/migrations/`, as `analytics_migrations`.
285///
286/// Apps made before 0.4 list them in `src/migrations/mod.rs`:
287/// `migrations! { m20261003115514_create_posts, … }`.
288#[proc_macro]
289pub fn migrations(input: TokenStream) -> TokenStream {
290    // `migrations!()` and `migrations!(analytics)`: found in `db/`.
291    let tokens = proc_macro2::TokenStream::from(input.clone());
292    let mut idents = tokens.clone().into_iter();
293    let database = match (idents.next(), idents.next()) {
294        (None, _) => Some(None),
295        (Some(proc_macro2::TokenTree::Ident(name)), None)
296            if !name.to_string().starts_with('m')
297                || !name.to_string()[1..].starts_with(|c: char| c.is_ascii_digit()) =>
298        {
299            Some(Some(name))
300        }
301        _ => None,
302    };
303    if let Some(database) = database {
304        return models::discovered_migrations(database)
305            .unwrap_or_else(syn::Error::into_compile_error)
306            .into();
307    }
308    let names = parse_macro_input!(input with controllers::Names::parse_terminated);
309    let here = Some(proc_macro::Span::call_site().local_file()).flatten();
310    models::migrations(names, here)
311        .unwrap_or_else(syn::Error::into_compile_error)
312        .into()
313}
314
315/// `clients!(stripe)`: declares an app's clients for other services, from
316/// `src/clients/<name>.glacier` (`client Stripe do … end`) or `<name>.rs`,
317/// re-exporting each.
318#[proc_macro]
319pub fn clients(input: TokenStream) -> TokenStream {
320    let names = parse_macro_input!(input with controllers::Names::parse_terminated);
321    models::expand(names, "client")
322        .unwrap_or_else(syn::Error::into_compile_error)
323        .into()
324}
325
326/// `folder!()` in a folder's `mod.rs` (`src/policies/mod.rs`): every
327/// `.glacier` and `.rs` file in the folder, declared and re-exported, with
328/// no list to keep.
329#[proc_macro]
330pub fn folder(input: TokenStream) -> TokenStream {
331    if !input.is_empty() {
332        return syn::Error::new(proc_macro2::Span::call_site(), "folder!() takes nothing")
333            .into_compile_error()
334            .into();
335    }
336    let here = Some(proc_macro::Span::call_site().local_file()).flatten();
337    models::folder(here)
338        .unwrap_or_else(syn::Error::into_compile_error)
339        .into()
340}
341
342/// `modules!(slack, helpers)`: declares an app's modules from
343/// `src/<name>.glacier` (`module Slack do … end`) or `src/<name>.rs`,
344/// re-exporting each, for `src/lib.rs`.
345#[proc_macro]
346pub fn modules(input: TokenStream) -> TokenStream {
347    let names = parse_macro_input!(input with controllers::Names::parse_terminated);
348    models::expand(names, "module")
349        .unwrap_or_else(syn::Error::into_compile_error)
350        .into()
351}
352
353/// `middleware!(require_admin)`: declares an app's middleware, from
354/// `src/middleware/<name>.glacier` (`middleware RequireAdmin do … end`) or
355/// `<name>.rs`, re-exporting each.
356#[proc_macro]
357pub fn middleware(input: TokenStream) -> TokenStream {
358    let names = parse_macro_input!(input with controllers::Names::parse_terminated);
359    models::expand(names, "middleware")
360        .unwrap_or_else(syn::Error::into_compile_error)
361        .into()
362}
363
364/// `mailers!(report_mailer)`: declares an app's mailers, from
365/// `src/mailers/<name>.glacier` (`mailer ReportMailer do … end`) or
366/// `<name>.rs`, re-exporting each.
367#[proc_macro]
368pub fn mailers(input: TokenStream) -> TokenStream {
369    let names = parse_macro_input!(input with controllers::Names::parse_terminated);
370    models::expand(names, "mailer")
371        .unwrap_or_else(syn::Error::into_compile_error)
372        .into()
373}
374
375/// `serializers!(country_serializer)`: declares an app's serializer
376/// modules, from `src/serializers/<name>.glacier` (compiled into
377/// `.glacier/serializers/`) or `<name>.rs`, re-exporting each serializer.
378#[proc_macro]
379pub fn serializers(input: TokenStream) -> TokenStream {
380    let names = parse_macro_input!(input with controllers::Names::parse_terminated);
381    models::expand(names, "serializer")
382        .unwrap_or_else(syn::Error::into_compile_error)
383        .into()
384}
385
386/// The app's configuration: `Config::load()` (reading `config/*.toml`) in
387/// debug builds, and the same files compiled into the binary in release
388/// builds. Environment variables override either.
389///
390/// ```ignore
391/// let config = glacier::config!()?;
392/// ```
393#[proc_macro]
394pub fn config(input: TokenStream) -> TokenStream {
395    embed::config(input.into())
396        .unwrap_or_else(syn::Error::into_compile_error)
397        .into()
398}
399
400/// Middleware serving a folder of static files: from disk in debug builds,
401/// and from copies compiled into the binary in release builds, with ETags
402/// from their contents.
403///
404/// ```ignore
405/// App::new().middleware(glacier::static_files!("public"))
406/// ```
407#[proc_macro]
408pub fn static_files(input: TokenStream) -> TokenStream {
409    let dir = parse_macro_input!(input as LitStr);
410    embed::static_files(dir)
411        .unwrap_or_else(syn::Error::into_compile_error)
412        .into()
413}
414
415/// An async test, run on a single-threaded Tokio runtime, so apps don't
416/// need Tokio as a dependency.
417///
418/// `#[glacier::test(app)]` runs it against the app declared by
419/// `glacier::tests!` (a fresh database, and the ambient client behind
420/// `glacier::testing::get` and friends); `setup(a, b)` runs those async
421/// functions first. `.glacier` tests compile to this.
422#[proc_macro_attribute]
423pub fn test(args: TokenStream, item: TokenStream) -> TokenStream {
424    let args = match test::Args::parse(args.into()) {
425        Ok(args) => args,
426        Err(e) => return e.into_compile_error().into(),
427    };
428    let func = parse_macro_input!(item as ItemFn);
429    test::expand(args, func)
430        .unwrap_or_else(syn::Error::into_compile_error)
431        .into()
432}
433
434/// `tests!(controllers::posts, factories::post)`: declares an app's
435/// `.glacier` test files (`tests/controllers/posts.test.glacier`,
436/// `tests/factories/post.glacier`) as modules of the test crate, nested
437/// like their folders, and the app they test.
438#[proc_macro]
439pub fn tests(input: TokenStream) -> TokenStream {
440    let files = parse_macro_input!(input with tests::Files::parse_terminated);
441    tests::expand(files)
442        .unwrap_or_else(syn::Error::into_compile_error)
443        .into()
444}
445
446/// Marks the async entry point of a Glacier application, starting a
447/// multi-threaded Tokio runtime. Apps don't need to depend on Tokio directly.
448#[proc_macro_attribute]
449pub fn main(args: TokenStream, item: TokenStream) -> TokenStream {
450    let args = proc_macro2::TokenStream::from(args);
451    if !args.is_empty() {
452        return syn::Error::new_spanned(args, "#[glacier::main] takes no arguments")
453            .into_compile_error()
454            .into();
455    }
456
457    let func = parse_macro_input!(item as ItemFn);
458    if func.sig.asyncness.is_none() {
459        return syn::Error::new_spanned(
460            func.sig.fn_token,
461            "#[glacier::main] requires an `async fn`",
462        )
463        .into_compile_error()
464        .into();
465    }
466
467    let attrs = &func.attrs;
468    let vis = &func.vis;
469    let body = &func.block;
470    let mut sig = func.sig.clone();
471    sig.asyncness = None;
472
473    quote! {
474        #(#attrs)*
475        #vis #sig {
476            ::glacier::__private::tokio::runtime::Builder::new_multi_thread()
477                .enable_all()
478                // Room for deep async call chains in debug builds; Tokio's
479                // default is 2 MB.
480                .thread_stack_size(8 * 1024 * 1024)
481                .build()
482                .expect("failed to start the Tokio runtime")
483                .block_on(async move #body)
484        }
485    }
486    .into()
487}