1use 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
21enum WelSchemaInput {
27 Templates { form_id: Ident },
29 Path { path: LitStr },
31}
32
33struct 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
45enum WellformedInput {
52 DefaultPath,
53 Schema(WelSchemaInput),
54 Module(FormSchemaInput),
55}
56
57impl Parse for WelSchemaInput {
58 fn parse(input: ParseStream) -> syn::Result<Self> {
59 if input.peek(Ident) {
61 let first: Ident = input.parse()?;
62
63 if first == "templates" {
64 let _: Token![::] = input.parse()?;
66
67 let form_id: Ident = input.parse()?;
69
70 if input.peek(Token![::]) {
72 let _: Token![::] = input.parse()?;
73 let _const_name: Ident = input.parse()?;
74 }
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 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#[proc_macro]
186pub fn wel_schema(input: TokenStream) -> TokenStream {
187 let input = parse_macro_input!(input as WelSchemaInput);
188
189 let (full_path, form_dir, span): (PathBuf, Option<PathBuf>, Span) = match &input {
191 WelSchemaInput::Templates { form_id } => {
192 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 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 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 let form_dir = full_path.parent().map(|p| p.to_path_buf());
225 (full_path, form_dir, path.span())
226 }
227 };
228
229 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 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 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#[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#[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
439fn find_templates_dir(start: &Path) -> Option<PathBuf> {
441 let mut current = start.to_path_buf();
442
443 for _ in 0..10 {
445 let templates = current.join("templates");
447 if templates.is_dir() && templates.join("src").is_dir() {
448 return Some(templates);
449 }
450
451 if !current.pop() {
453 break;
454 }
455 }
456
457 None
458}