1use std::path::{Path, PathBuf};
7
8use proc_macro::TokenStream;
9use proc_macro2::Span;
10use quote::{format_ident, quote};
11use syn::parse::{Parse, ParseStream};
12use syn::{FnArg, ItemFn, LitStr, Pat, parse_macro_input};
13
14fn manifest_dir() -> PathBuf {
15 std::env::var_os("CARGO_MANIFEST_DIR").map(PathBuf::from).unwrap_or_else(|| PathBuf::from("."))
16}
17
18fn caller_file() -> Option<PathBuf> {
22 let file = proc_macro::Span::call_site().local_file()?;
23 if file.is_absolute() {
24 return Some(file);
25 }
26 let from_cwd = std::env::current_dir().ok().map(|d| d.join(&file));
27 match from_cwd {
28 Some(p) if p.exists() => Some(p),
29 _ => Some(manifest_dir().join(file)),
30 }
31}
32
33fn caller_dir() -> PathBuf {
35 caller_file().and_then(|f| f.parent().map(Path::to_path_buf)).unwrap_or_else(manifest_dir)
36}
37
38fn caller_file_relative() -> Option<String> {
39 let abs = caller_file()?;
40 let abs = std::fs::canonicalize(&abs).unwrap_or(abs);
41 let manifest = std::fs::canonicalize(manifest_dir()).unwrap_or_else(|_| manifest_dir());
42 let rel = abs.strip_prefix(&manifest).map(Path::to_path_buf).unwrap_or(abs);
43 Some(rel.components().map(|c| c.as_os_str().to_string_lossy()).collect::<Vec<_>>().join("/"))
44}
45
46fn error(span: Span, msg: impl std::fmt::Display) -> TokenStream {
47 syn::Error::new(span, msg).to_compile_error().into()
48}
49
50struct ClientArgs {
55 module: Option<LitStr>,
56}
57
58impl Parse for ClientArgs {
59 fn parse(input: ParseStream) -> syn::Result<Self> {
60 if input.is_empty() {
61 return Ok(ClientArgs { module: None });
62 }
63 let key: syn::Ident = input.parse()?;
64 if key != "module" {
65 return Err(syn::Error::new(key.span(), "expected `module = \"/path/to/island.js\"`"));
66 }
67 input.parse::<syn::Token![=]>()?;
68 Ok(ClientArgs { module: Some(input.parse()?) })
69 }
70}
71
72#[proc_macro_attribute]
95pub fn client(attr: TokenStream, item: TokenStream) -> TokenStream {
96 let args = parse_macro_input!(attr as ClientArgs);
97 let func = parse_macro_input!(item as ItemFn);
98 if func.sig.asyncness.is_some() {
99 return error(
100 func.sig.ident.span(),
101 "#[client] components must be synchronous; load data in the page and pass it as props",
102 );
103 }
104 if !func.sig.generics.params.is_empty() {
105 return error(func.sig.generics.span_or_ident(&func.sig.ident), "#[client] components cannot be generic");
106 }
107 let mut names = Vec::new();
108 for input in &func.sig.inputs {
109 match input {
110 FnArg::Typed(t) => match &*t.pat {
111 Pat::Ident(p) => names.push(p.ident.clone()),
112 other => {
113 return error(syn::spanned::Spanned::span(other), "#[client] arguments must be plain identifiers");
114 }
115 },
116 FnArg::Receiver(r) => return error(syn::spanned::Spanned::span(r), "#[client] cannot be a method"),
117 }
118 }
119 let vis = &func.vis;
120 let attrs = &func.attrs;
121 let name = &func.sig.ident;
122 let name_str = name.to_string();
123 let inputs = &func.sig.inputs;
124 let output = &func.sig.output;
125 let block = &func.block;
126 let keys = names.iter().map(|n| n.to_string().trim_start_matches("r#").to_owned());
127 let module = match &args.module {
128 Some(m) => quote!(::core::option::Option::Some(#m)),
129 None => quote!(::core::option::Option::None),
130 };
131 quote! {
132 #(#attrs)*
133 #[allow(non_snake_case)]
134 #vis fn #name(#inputs) -> ::next_rust::Node {
135 let __nr_props = ::next_rust::__private::island_props(&[
136 #( (#keys, ::next_rust::__private::to_json_value(&#names)) ),*
137 ]);
138 #[allow(non_snake_case)]
139 fn __nr_render(#inputs) #output #block
140 ::next_rust::__private::island(#name_str, #module, __nr_props, __nr_render(#(#names),*))
141 }
142 }
143 .into()
144}
145
146trait SpanOrIdent {
147 fn span_or_ident(&self, ident: &syn::Ident) -> Span;
148}
149
150impl SpanOrIdent for syn::Generics {
151 fn span_or_ident(&self, ident: &syn::Ident) -> Span {
152 self.lt_token.map(|t| t.span).unwrap_or_else(|| ident.span())
153 }
154}
155
156#[proc_macro_attribute]
167pub fn server(attr: TokenStream, item: TokenStream) -> TokenStream {
168 if !attr.is_empty() {
169 return error(Span::call_site(), "#[server] takes no arguments");
170 }
171 let item = proc_macro2::TokenStream::from(item);
172 quote!(#[cfg(not(target_arch = "wasm32"))] #item).into()
173}
174
175#[proc_macro_attribute]
204pub fn server_action(attr: TokenStream, item: TokenStream) -> TokenStream {
205 let mut body_limit: Option<syn::Expr> = None;
206 if !attr.is_empty() {
207 let parser = syn::meta::parser(|meta| {
208 if meta.path.is_ident("body_limit") {
209 if body_limit.is_some() {
210 return Err(meta.error("`body_limit` is given twice"));
211 }
212 body_limit = Some(meta.value()?.parse()?);
213 Ok(())
214 } else {
215 Err(meta.error("unknown #[server_action] argument; the only one is `body_limit = <bytes>`"))
216 }
217 });
218 parse_macro_input!(attr with parser);
219 }
220 let func = parse_macro_input!(item as ItemFn);
221 let name = &func.sig.ident;
222 let argc = func.sig.inputs.len();
223 if argc > 2 {
224 return error(
225 name.span(),
226 "server actions take no arguments, one input, an ActionContext, or (ActionContext, input)",
227 );
228 }
229 if matches!(func.sig.inputs.first(), Some(FnArg::Receiver(_))) {
230 return error(name.span(), "server actions cannot be methods");
231 }
232 let id_const = format_ident!("__NR_ACTION_ID_{}", name);
233 let handler = format_ident!("__nr_action_{}", name);
234 let id = match caller_file_relative() {
235 Some(file) => quote!(concat!(#file, "::", stringify!(#name))),
236 None => quote!(concat!(module_path!(), "::", stringify!(#name))),
237 };
238 let context_only = argc == 1
240 && matches!(func.sig.inputs.first(), Some(FnArg::Typed(arg))
241 if matches!(&*arg.ty, syn::Type::Path(p)
242 if p.path.segments.last().is_some_and(|s| s.ident == "ActionContext")));
243 let call = match (argc, func.sig.asyncness.is_some()) {
244 (1, true) if context_only => quote!(::next_rust::__private::run_action_ctx0(req, #name)),
245 (1, false) if context_only => {
246 quote!(::next_rust::__private::run_action_ctx0(req, |c| async move { #name(c) }))
247 }
248 (0, true) => quote!(::next_rust::__private::run_action0(req, #name)),
249 (1, true) => quote!(::next_rust::__private::run_action(req, #name)),
250 (2, true) => quote!(::next_rust::__private::run_action_ctx(req, #name)),
251 (0, false) => quote!(::next_rust::__private::run_action0(req, || async move { #name() })),
252 (1, false) => quote!(::next_rust::__private::run_action(req, |i| async move { #name(i) })),
253 _ => quote!(::next_rust::__private::run_action_ctx(req, |c, i| async move { #name(c, i) })),
254 };
255 let limit = body_limit.map(|bytes| {
256 quote! {
257 const __NR_BODY_LIMIT: usize = #bytes;
258 let mut req = req;
259 req.set_body_limit(__NR_BODY_LIMIT);
260 }
261 });
262 quote! {
263 #[cfg(not(target_arch = "wasm32"))]
264 #func
265
266 #[doc(hidden)]
267 #[allow(non_upper_case_globals)]
268 pub const #id_const: &str = #id;
269
270 #[doc(hidden)]
271 #[cfg(not(target_arch = "wasm32"))]
272 pub fn #handler(req: ::next_rust::Request) -> ::next_rust::BoxFuture<::next_rust::Response> {
273 #limit
274 ::std::boxed::Box::pin(#call)
275 }
276 }
277 .into()
278}
279
280#[proc_macro]
284pub fn action(input: TokenStream) -> TokenStream {
285 let mut path = parse_macro_input!(input as syn::Path);
286 let Some(last) = path.segments.last_mut() else { return error(Span::call_site(), "expected a function path") };
287 last.ident = format_ident!("__NR_ACTION_ID_{}", last.ident);
288 quote!(::next_rust::ActionRef::new(#path)).into()
289}
290
291fn read_relative(lit: &LitStr, base: &Path) -> Result<(PathBuf, String), TokenStream> {
296 let rel = lit.value();
297 let direct = base.join(&rel);
298 let path = if direct.is_file() {
299 direct
300 } else {
301 match find_unique(&search_roots(), Path::new(&rel)) {
305 Found::One(p) => p,
306 Found::Many(list) => {
307 let names: Vec<String> = list.iter().map(|p| p.display().to_string()).collect();
308 return Err(error(
309 lit.span(),
310 format!(
311 "`{rel}` matches several files; use a path relative to this source file:\n {}",
312 names.join("\n ")
313 ),
314 ));
315 }
316 Found::None => {
317 return Err(error(
318 lit.span(),
319 format!("cannot find `{rel}` (looked next to this file and in the project)"),
320 ));
321 }
322 }
323 };
324 match std::fs::read_to_string(&path) {
325 Ok(text) => Ok((path, text)),
326 Err(e) => Err(error(lit.span(), format!("cannot read {}: {e}", path.display()))),
327 }
328}
329
330enum Found {
331 None,
332 One(PathBuf),
333 Many(Vec<PathBuf>),
334}
335
336fn search_roots() -> Vec<PathBuf> {
338 let manifest = manifest_dir();
339 let mut roots = Vec::new();
340 let app = std::fs::read_to_string(manifest.join("next-rust.toml"))
341 .ok()
342 .and_then(|toml| configured_app_dir(&toml))
343 .unwrap_or_else(|| "app".to_owned());
344 roots.push(manifest.join(app));
345 roots.push(manifest);
346 roots
347}
348
349fn configured_app_dir(toml: &str) -> Option<String> {
351 let mut in_app = false;
352 for line in toml.lines() {
353 let line = line.split('#').next().unwrap_or("").trim();
354 if line.starts_with('[') {
355 in_app = line == "[app]";
356 } else if in_app && let Some(value) = line.strip_prefix("directory") {
357 let value = value.trim_start().strip_prefix('=')?.trim().trim_matches('"');
358 return Some(value.to_owned());
359 }
360 }
361 None
362}
363
364fn find_unique(roots: &[PathBuf], rel: &Path) -> Found {
367 for root in roots {
368 let mut matches = Vec::new();
369 collect_matches(root, rel, 0, &mut matches);
370 matches.sort();
371 matches.dedup();
372 match matches.len() {
373 0 => continue,
374 1 => return Found::One(matches.remove(0)),
375 _ => return Found::Many(matches),
376 }
377 }
378 Found::None
379}
380
381fn collect_matches(dir: &Path, rel: &Path, depth: usize, out: &mut Vec<PathBuf>) {
382 if depth > 12 || out.len() > 16 {
383 return;
384 }
385 let Ok(entries) = std::fs::read_dir(dir) else { return };
386 for entry in entries.flatten() {
387 let path = entry.path();
388 let name = entry.file_name();
389 let name = name.to_string_lossy();
390 let Ok(kind) = entry.file_type() else { continue };
391 if kind.is_dir() {
392 if !name.starts_with('.') && name != "target" && name != "node_modules" {
393 collect_matches(&path, rel, depth + 1, out);
394 }
395 } else if path.ends_with(rel) {
396 out.push(path);
397 }
398 }
399}
400
401fn field_ident(class: &str) -> Option<syn::Ident> {
402 let name: String = class.chars().map(|c| if c.is_ascii_alphanumeric() || c == '_' { c } else { '_' }).collect();
403 if name.is_empty() || name.starts_with(|c: char| c.is_ascii_digit()) {
404 return None;
405 }
406 syn::parse_str::<syn::Ident>(&name).ok().or_else(|| Some(syn::Ident::new_raw(&name, Span::call_site())))
407}
408
409#[proc_macro]
422pub fn css_module(input: TokenStream) -> TokenStream {
423 let lit = parse_macro_input!(input as LitStr);
424 let (path, text) = match read_relative(&lit, &caller_dir()) {
425 Ok(v) => v,
426 Err(e) => return e,
427 };
428 let salt = path.strip_prefix(manifest_dir()).unwrap_or(&path).to_string_lossy().replace('\\', "/");
429 let usage = CssUsage::load();
430 let text = match &usage {
431 Some(u) => next_rust_assets::css::prune(&next_rust_assets::css::minify(&text), &|name| {
433 u.names.contains(name) || u.names.contains(&name.replace('-', "_"))
434 }),
435 None => text,
436 };
437 let track = usage.as_ref().map(CssUsage::track);
438 let out = next_rust_assets::css::scope(&text, &salt, true);
439 let id = next_rust_assets::content_hash(out.css.as_bytes())[..12].to_owned();
440 let css = out.css;
441 let abs = path.to_string_lossy().into_owned();
442 let mut seen = std::collections::HashMap::new();
443 let mut fields = Vec::new();
444 let mut values = Vec::new();
445 for (class, scoped) in &out.classes {
446 let Some(ident) = field_ident(class) else {
447 return error(lit.span(), format!("class `{class}` cannot be used as a Rust field name"));
448 };
449 if let Some(prev) = seen.insert(ident.to_string(), class.clone()) {
450 return error(lit.span(), format!("classes `{prev}` and `{class}` map to the same field `{ident}`"));
451 }
452 fields.push(quote!(pub #ident: ::next_rust::CssClass));
453 values.push(quote!(#ident: ::next_rust::CssClass::new(#scoped, &__NR_SHEET)));
454 }
455 quote! {{
456 const _: &[u8] = include_bytes!(#abs);
457 #track
458 static __NR_SHEET: ::next_rust::Stylesheet = ::next_rust::Stylesheet { id: #id, css: #css, per_class: None, scripts: &[] };
459 #[allow(non_camel_case_types, dead_code)]
460 #[derive(Clone, Copy)]
461 struct __NrCssModule { #(#fields,)* }
462 __NrCssModule { #(#values,)* }
463 }}
464 .into()
465}
466
467#[proc_macro]
471pub fn global_css(input: TokenStream) -> TokenStream {
472 let lit = parse_macro_input!(input as LitStr);
473 let (path, text) = match read_relative(&lit, &caller_dir()) {
474 Ok(v) => v,
475 Err(e) => return e,
476 };
477 let css = next_rust_assets::css::minify(&text);
478 let usage = CssUsage::load();
479 let css = match &usage {
480 Some(u) => next_rust_assets::css::prune(&css, &|name| u.names.contains(name)),
481 None => css,
482 };
483 let track = usage.as_ref().map(CssUsage::track);
484 let id = next_rust_assets::content_hash(css.as_bytes())[..12].to_owned();
485 let abs = path.to_string_lossy().into_owned();
486 let keep = CssUsage::keep_classes();
490 quote! {{
491 const _: &[u8] = include_bytes!(#abs);
492 #track
493 static __NR_KEEP: &[&str] = &[#(#keep),*];
494 static __NR_SHEET: ::next_rust::Stylesheet = ::next_rust::Stylesheet { id: #id, css: #css, per_class: Some(__NR_KEEP), scripts: &[] };
495 &__NR_SHEET
496 }}
497 .into()
498}
499
500struct CssUsage {
504 names: std::collections::HashSet<String>,
505 file: String,
506}
507
508impl CssUsage {
509 fn load() -> Option<Self> {
510 let file = PathBuf::from(std::env::var_os("OUT_DIR")?).join("next_rust_css_usage.txt");
511 let text = std::fs::read_to_string(&file).ok()?;
512 Some(CssUsage { names: text.lines().map(str::to_owned).collect(), file: file.to_string_lossy().into_owned() })
513 }
514
515 fn keep_classes() -> Vec<String> {
518 std::env::var_os("OUT_DIR")
519 .map(|out| PathBuf::from(out).join("next_rust_css_keep.txt"))
520 .and_then(|file| std::fs::read_to_string(file).ok())
521 .map(|text| text.lines().map(str::trim).filter(|l| !l.is_empty()).map(str::to_owned).collect())
522 .unwrap_or_default()
523 }
524
525 fn track(&self) -> proc_macro2::TokenStream {
527 let file = &self.file;
528 quote!(
529 const _: &[u8] = include_bytes!(#file);
530 )
531 }
532}
533
534#[proc_macro]
539pub fn asset(input: TokenStream) -> TokenStream {
540 let lit = parse_macro_input!(input as LitStr);
541 let rel = lit.value();
542 let rel = rel.trim_start_matches('/');
543 if rel.split('/').any(|s| s == ".." || s.starts_with('.')) {
544 return error(lit.span(), "asset paths must stay inside assets/ and not reference hidden files");
545 }
546 let path = manifest_dir().join("assets").join(rel);
547 let bytes = match std::fs::read(&path) {
548 Ok(b) => b,
549 Err(e) => return error(lit.span(), format!("cannot read {}: {e}", path.display())),
550 };
551 let (dir, file) = match rel.rsplit_once('/') {
552 Some((d, f)) => (format!("{d}/"), f.to_owned()),
553 None => (String::new(), rel.to_owned()),
554 };
555 let served = std::env::var_os("OUT_DIR")
558 .map(|out| PathBuf::from(out).join("next_rust_min").join("assets").join(rel))
559 .and_then(|min| std::fs::read(min).ok())
560 .unwrap_or(bytes);
561 let url = format!("/_next-rust/assets/{dir}{}", next_rust_assets::fingerprint_name(&file, &served));
562 let abs = path.to_string_lossy().into_owned();
563 quote! {{
564 const _: &[u8] = include_bytes!(#abs);
565 #url
566 }}
567 .into()
568}
569
570#[cfg(test)]
571mod tests {
572 use super::*;
573
574 fn temp(name: &str) -> PathBuf {
575 let dir = std::env::temp_dir().join(format!("nr-macros-{name}-{}", std::process::id()));
576 let _ = std::fs::remove_dir_all(&dir);
577 dir
578 }
579
580 fn touch(path: PathBuf) {
581 std::fs::create_dir_all(path.parent().unwrap()).unwrap();
582 std::fs::write(path, "body{}").unwrap();
583 }
584
585 #[test]
586 fn finds_a_stylesheet_inside_the_app_directory() {
587 let root = temp("unique");
588 touch(root.join("app/globals.css"));
589 touch(root.join("target/debug/globals.css"));
590 let roots = vec![root.join("app"), root.clone()];
591 assert!(
592 matches!(find_unique(&roots, Path::new("globals.css")), Found::One(p) if p == root.join("app/globals.css"))
593 );
594 std::fs::remove_dir_all(root).unwrap();
595 }
596
597 #[test]
598 fn app_directory_wins_and_ambiguity_is_reported() {
599 let root = temp("many");
600 touch(root.join("app/a/card.css"));
601 touch(root.join("app/b/card.css"));
602 touch(root.join("styles/card.css"));
603 let roots = vec![root.join("app"), root.clone()];
604 assert!(matches!(find_unique(&roots, Path::new("card.css")), Found::Many(list) if list.len() == 2));
605 assert!(matches!(find_unique(&roots, Path::new("a/card.css")), Found::One(_)));
606 assert!(matches!(find_unique(&roots, Path::new("missing.css")), Found::None));
607 std::fs::remove_dir_all(root).unwrap();
608 }
609
610 #[test]
611 fn reads_the_configured_app_directory() {
612 assert_eq!(
613 configured_app_dir("[server]\nport = 1\n[app]\ndirectory = \"src/web\" # routes\n").as_deref(),
614 Some("src/web")
615 );
616 assert_eq!(configured_app_dir("[build]\ndirectory = \"x\"\n"), None);
617 }
618}