Skip to main content

wellformed_macros/
lib.rs

1//! Proc macros for generating Rust types from wellformed schemas.
2//!
3//! # Example
4//!
5//! ```ignore
6//! use wellformed_macros::wellformed;
7//!
8//! // Load from a local path relative to CARGO_MANIFEST_DIR:
9//! let signup = wellformed!("schemas/signup.json");
10//! ```
11
12use proc_macro::TokenStream;
13use proc_macro2::Span;
14use quote::{quote, ToTokens};
15use std::path::{Path, PathBuf};
16use syn::parse::{Parse, ParseStream};
17use syn::{parse_macro_input, Ident, LitStr, Token, Visibility};
18use wellformed::codegen::{generate_all, generate_form_module, CodegenOptions, GeneratedCode};
19use wellformed::Schema;
20
21/// Input to the wel_schema! macro.
22///
23/// Supports two forms:
24/// - `wel_schema!("path/to/schema.json")` - loads relative to CARGO_MANIFEST_DIR
25/// - `wel_schema!(templates::form_id)` - loads from templates/src/form_id/schema.json
26enum WelSchemaInput {
27    /// templates::<form_id> or templates::<form_id>::SCHEMA_JSON
28    Templates { form_id: Ident },
29    /// Literal path string
30    Path { path: LitStr },
31}
32
33/// Input to the form_schema! macro.
34///
35/// Syntax:
36/// `form_schema!(pub mod signup = "schemas/signup.json");`
37struct FormSchemaInput {
38    visibility: Visibility,
39    module_name: Ident,
40    path: LitStr,
41    runtime_path: Option<syn::Path>,
42    client_path: Option<syn::Path>,
43}
44
45/// Input to the wellformed! macro.
46///
47/// - `wellformed!("path/to/schema.json")` embeds a schema value.
48/// - `wellformed!()` embeds `schema.json` relative to CARGO_MANIFEST_DIR.
49/// - `wellformed!(pub mod signup = "schemas/signup.json")` is accepted as a
50///   compatibility alias for `form_schema!`.
51enum WellformedInput {
52    DefaultPath,
53    Schema(WelSchemaInput),
54    Module(FormSchemaInput),
55}
56
57impl Parse for WelSchemaInput {
58    fn parse(input: ParseStream) -> syn::Result<Self> {
59        // Try to parse `templates::form_id` syntax
60        if input.peek(Ident) {
61            let first: Ident = input.parse()?;
62
63            if first == "templates" {
64                // Expect ::
65                let _: Token![::] = input.parse()?;
66
67                // Get form_id
68                let form_id: Ident = input.parse()?;
69
70                // Optionally consume ::SCHEMA_JSON if present
71                if input.peek(Token![::]) {
72                    let _: Token![::] = input.parse()?;
73                    let _const_name: Ident = input.parse()?;
74                    // We ignore the constant name - always use schema.json
75                }
76
77                return Ok(WelSchemaInput::Templates { form_id });
78            } else {
79                return Err(syn::Error::new(
80                    first.span(),
81                    "expected 'templates' or a string literal",
82                ));
83            }
84        }
85
86        // Otherwise parse as a path string
87        let path: LitStr = input.parse()?;
88        Ok(WelSchemaInput::Path { path })
89    }
90}
91
92impl Parse for FormSchemaInput {
93    fn parse(input: ParseStream) -> syn::Result<Self> {
94        let visibility: Visibility = input.parse()?;
95        let _: Token![mod] = input.parse()?;
96        let module_name: Ident = input.parse()?;
97        let _: Token![=] = input.parse()?;
98        let path: LitStr = input.parse()?;
99        let mut runtime_path = None;
100        let mut client_path = None;
101        while input.peek(Token![,]) {
102            let _: Token![,] = input.parse()?;
103            if input.is_empty() {
104                break;
105            }
106            let key: Ident = input.parse()?;
107            let _: Token![=] = input.parse()?;
108            if key == "runtime" {
109                runtime_path = Some(input.parse()?);
110            } else if key == "client" {
111                client_path = Some(input.parse()?);
112            } else {
113                return Err(syn::Error::new(
114                    key.span(),
115                    "expected `runtime = path` or `client = path`",
116                ));
117            }
118        }
119
120        if input.peek(Token![;]) {
121            let _: Token![;] = input.parse()?;
122        }
123
124        Ok(Self {
125            visibility,
126            module_name,
127            path,
128            runtime_path,
129            client_path,
130        })
131    }
132}
133
134impl Parse for WellformedInput {
135    fn parse(input: ParseStream) -> syn::Result<Self> {
136        if input.is_empty() {
137            return Ok(Self::DefaultPath);
138        }
139
140        let fork = input.fork();
141        let _visibility: Visibility = fork.parse()?;
142        if fork.peek(Token![mod]) {
143            return Ok(Self::Module(input.parse()?));
144        }
145
146        Ok(Self::Schema(input.parse()?))
147    }
148}
149
150/// Generate Rust types from a wellformed schema file.
151///
152/// The macro reads the schema file at compile time and generates:
153/// - Struct definitions with serde derives
154/// - A `validate()` method that runs wellformed validation
155///
156/// For Axum handlers, repository traits, and OpenAPI constants, use the
157/// lower-level `wellformed::codegen::generate_all` API with
158/// `CodegenOptions { generate_api: true, .. }` so the consuming application can
159/// explicitly provide the generated web dependencies. PDF render handlers also
160/// require `generate_pdf_handlers: true` and app-level rendering dependencies.
161///
162/// # Examples
163///
164/// Load from a local path:
165/// ```ignore
166/// wel_schema!("schemas/signup.json");
167/// ```
168///
169/// Load from a templates workspace:
170/// ```ignore
171/// wel_schema!(templates::signup);
172/// // Or with explicit constant:
173/// wel_schema!(templates::signup::SCHEMA_JSON);
174/// ```
175///
176/// Use the generated types:
177/// ```ignore
178/// let form = Signup {
179///     email: "ada@example.com".to_string(),
180///     ..Default::default()
181/// };
182///
183/// let result = form.validate();
184/// ```
185#[proc_macro]
186pub fn wel_schema(input: TokenStream) -> TokenStream {
187    let input = parse_macro_input!(input as WelSchemaInput);
188
189    // Track the form directory for PDF path resolution (absolute path)
190    let (full_path, form_dir, span): (PathBuf, Option<PathBuf>, Span) = match &input {
191        WelSchemaInput::Templates { form_id } => {
192            // Resolve path to templates/src/{form_id}/schema.json
193            let manifest_dir =
194                std::env::var("CARGO_MANIFEST_DIR").expect("CARGO_MANIFEST_DIR not set");
195            let manifest_path = PathBuf::from(&manifest_dir);
196
197            // Walk up to find workspace root (look for templates directory)
198            let templates_dir = find_templates_dir(&manifest_path);
199            let (schema_path, form_directory) = match templates_dir {
200                Some(dir) => {
201                    let form_dir = dir.join("src").join(form_id.to_string());
202                    let schema_path = form_dir.join("schema.json");
203                    (schema_path, Some(form_dir))
204                }
205                None => {
206                    let msg = format!(
207                        "Could not find templates directory. Searched from '{}'",
208                        manifest_path.display()
209                    );
210                    return syn::Error::new(form_id.span(), msg)
211                        .to_compile_error()
212                        .into();
213                }
214            };
215
216            (schema_path, form_directory, form_id.span())
217        }
218        WelSchemaInput::Path { path } => {
219            // Resolve path relative to CARGO_MANIFEST_DIR
220            let manifest_dir =
221                std::env::var("CARGO_MANIFEST_DIR").expect("CARGO_MANIFEST_DIR not set");
222            let full_path = PathBuf::from(&manifest_dir).join(path.value());
223            // For path-based schemas, the form directory is the parent of the schema file
224            let form_dir = full_path.parent().map(|p| p.to_path_buf());
225            (full_path, form_dir, path.span())
226        }
227    };
228
229    // Read and parse schema
230    let content = match std::fs::read_to_string(&full_path) {
231        Ok(c) => c,
232        Err(e) => {
233            let msg = format!(
234                "Failed to read schema file '{}': {}",
235                full_path.display(),
236                e
237            );
238            return syn::Error::new(span, msg).to_compile_error().into();
239        }
240    };
241
242    let schema: Schema = match serde_json::from_str(&content) {
243        Ok(s) => s,
244        Err(e) => {
245            let msg = format!("Failed to parse schema JSON: {}", e);
246            return syn::Error::new(span, msg).to_compile_error().into();
247        }
248    };
249
250    // Generate code with options including PDF base path
251    let options = CodegenOptions {
252        pdf_base_path: form_dir.map(|p| p.to_string_lossy().to_string()),
253        ..Default::default()
254    };
255    let GeneratedCode { code } = generate_all(&schema, &content, &options);
256
257    // Parse generated code as TokenStream
258    match code.parse() {
259        Ok(ts) => ts,
260        Err(e) => {
261            let msg = format!("Failed to parse generated code: {}", e);
262            syn::Error::new(span, msg).to_compile_error().into()
263        }
264    }
265}
266
267/// Embed a wellformed schema file as a value.
268///
269/// This is the preferred public macro for Rust applications that want a schema
270/// value they can assign to a local, static, or const binding. Use
271/// `form_schema!` when you want generated Rust types and a namespaced module
272/// facade.
273///
274/// ```ignore
275/// use wellformed_macros::wellformed;
276///
277/// let signup = wellformed!("schemas/signup.json");
278///
279/// let (result, value) = signup.validate_json(r#"{"email":"ada@example.com"}"#)?;
280/// assert!(result.is_valid());
281/// ```
282#[proc_macro]
283pub fn wellformed(input: TokenStream) -> TokenStream {
284    let input = parse_macro_input!(input as WellformedInput);
285
286    match input {
287        WellformedInput::DefaultPath => expand_embedded_schema(None),
288        WellformedInput::Schema(input) => expand_embedded_schema(Some(input)),
289        WellformedInput::Module(input) => expand_form_schema(input),
290    }
291}
292
293/// Generate a namespaced form module from a wellformed schema file.
294///
295/// Unlike `wel_schema!`, this macro does not emit free-floating generated
296/// items. It creates a module with typed values, validation helpers, field
297/// metadata, schema constants, and framework-neutral form state aliases.
298///
299/// ```ignore
300/// use wellformed_macros::form_schema;
301///
302/// form_schema!(pub mod signup = "schemas/signup.json");
303///
304/// let values = signup::validate_json(r#"{"email":"ada@example.com"}"#)?;
305/// let first_field = &signup::FIELDS[0];
306/// ```
307#[proc_macro]
308pub fn form_schema(input: TokenStream) -> TokenStream {
309    let input = parse_macro_input!(input as FormSchemaInput);
310    expand_form_schema(input)
311}
312
313fn expand_embedded_schema(input: Option<WelSchemaInput>) -> TokenStream {
314    let (full_path, span) = match input {
315        None => {
316            let manifest_dir =
317                std::env::var("CARGO_MANIFEST_DIR").expect("CARGO_MANIFEST_DIR not set");
318            (
319                PathBuf::from(manifest_dir).join("schema.json"),
320                Span::call_site(),
321            )
322        }
323        Some(WelSchemaInput::Path { path }) => {
324            let manifest_dir =
325                std::env::var("CARGO_MANIFEST_DIR").expect("CARGO_MANIFEST_DIR not set");
326            (PathBuf::from(manifest_dir).join(path.value()), path.span())
327        }
328        Some(WelSchemaInput::Templates { form_id }) => {
329            let manifest_dir =
330                std::env::var("CARGO_MANIFEST_DIR").expect("CARGO_MANIFEST_DIR not set");
331            let manifest_path = PathBuf::from(&manifest_dir);
332            let templates_dir = match find_templates_dir(&manifest_path) {
333                Some(dir) => dir,
334                None => {
335                    let msg = format!(
336                        "Could not find templates directory. Searched from '{}'",
337                        manifest_path.display()
338                    );
339                    return syn::Error::new(form_id.span(), msg)
340                        .to_compile_error()
341                        .into();
342                }
343            };
344            (
345                templates_dir
346                    .join("src")
347                    .join(form_id.to_string())
348                    .join("schema.json"),
349                form_id.span(),
350            )
351        }
352    };
353
354    let content = match std::fs::read_to_string(&full_path) {
355        Ok(c) => c,
356        Err(e) => {
357            let msg = format!(
358                "Failed to read schema file '{}': {}",
359                full_path.display(),
360                e
361            );
362            return syn::Error::new(span, msg).to_compile_error().into();
363        }
364    };
365
366    if let Err(e) = serde_json::from_str::<Schema>(&content) {
367        let msg = format!("Failed to parse schema JSON: {}", e);
368        return syn::Error::new(span, msg).to_compile_error().into();
369    }
370
371    let schema_json = LitStr::new(&content, span);
372    quote!(::wellformed::EmbeddedSchema::new(#schema_json)).into()
373}
374
375fn expand_form_schema(input: FormSchemaInput) -> TokenStream {
376    let manifest_dir = std::env::var("CARGO_MANIFEST_DIR").expect("CARGO_MANIFEST_DIR not set");
377    let full_path = PathBuf::from(&manifest_dir).join(input.path.value());
378
379    let content = match std::fs::read_to_string(&full_path) {
380        Ok(c) => c,
381        Err(e) => {
382            let msg = format!(
383                "Failed to read schema file '{}': {}",
384                full_path.display(),
385                e
386            );
387            return syn::Error::new(input.path.span(), msg)
388                .to_compile_error()
389                .into();
390        }
391    };
392
393    let schema: Schema = match serde_json::from_str(&content) {
394        Ok(s) => s,
395        Err(e) => {
396            let msg = format!("Failed to parse schema JSON: {}", e);
397            return syn::Error::new(input.path.span(), msg)
398                .to_compile_error()
399                .into();
400        }
401    };
402
403    let options = CodegenOptions {
404        pdf_base_path: full_path
405            .parent()
406            .map(|path| path.to_string_lossy().to_string()),
407        ..Default::default()
408    };
409    let visibility = input.visibility.to_token_stream().to_string();
410    let runtime_path = input
411        .runtime_path
412        .as_ref()
413        .map(|path| path.to_token_stream().to_string().replace(' ', ""));
414    let client_path = input
415        .client_path
416        .as_ref()
417        .map(|path| path.to_token_stream().to_string().replace(' ', ""));
418    let GeneratedCode { code } = generate_form_module(
419        &schema,
420        &content,
421        &input.module_name.to_string(),
422        &visibility,
423        runtime_path.as_deref(),
424        client_path.as_deref(),
425        &options,
426    );
427
428    match code.parse() {
429        Ok(ts) => ts,
430        Err(e) => {
431            let msg = format!("Failed to parse generated form module: {}", e);
432            syn::Error::new(input.module_name.span(), msg)
433                .to_compile_error()
434                .into()
435        }
436    }
437}
438
439/// Find the templates directory by walking up from the given path.
440fn find_templates_dir(start: &Path) -> Option<PathBuf> {
441    let mut current = start.to_path_buf();
442
443    // Walk up the directory tree
444    for _ in 0..10 {
445        // Check if templates directory exists here
446        let templates = current.join("templates");
447        if templates.is_dir() && templates.join("src").is_dir() {
448            return Some(templates);
449        }
450
451        // Move up one directory
452        if !current.pop() {
453            break;
454        }
455    }
456
457    None
458}