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]
198pub fn server_action(attr: TokenStream, item: TokenStream) -> TokenStream {
199 if !attr.is_empty() {
200 return error(Span::call_site(), "#[server_action] takes no arguments");
201 }
202 let func = parse_macro_input!(item as ItemFn);
203 let name = &func.sig.ident;
204 let argc = func.sig.inputs.len();
205 if argc > 2 {
206 return error(name.span(), "server actions take no arguments, one input, or (ActionContext, input)");
207 }
208 if matches!(func.sig.inputs.first(), Some(FnArg::Receiver(_))) {
209 return error(name.span(), "server actions cannot be methods");
210 }
211 let id_const = format_ident!("__NR_ACTION_ID_{}", name);
212 let handler = format_ident!("__nr_action_{}", name);
213 let id = match caller_file_relative() {
214 Some(file) => quote!(concat!(#file, "::", stringify!(#name))),
215 None => quote!(concat!(module_path!(), "::", stringify!(#name))),
216 };
217 let call = match (argc, func.sig.asyncness.is_some()) {
218 (0, true) => quote!(::next_rust::__private::run_action0(req, #name)),
219 (1, true) => quote!(::next_rust::__private::run_action(req, #name)),
220 (2, true) => quote!(::next_rust::__private::run_action_ctx(req, #name)),
221 (0, false) => quote!(::next_rust::__private::run_action0(req, || async move { #name() })),
222 (1, false) => quote!(::next_rust::__private::run_action(req, |i| async move { #name(i) })),
223 _ => quote!(::next_rust::__private::run_action_ctx(req, |c, i| async move { #name(c, i) })),
224 };
225 quote! {
226 #[cfg(not(target_arch = "wasm32"))]
227 #func
228
229 #[doc(hidden)]
230 #[allow(non_upper_case_globals)]
231 pub const #id_const: &str = #id;
232
233 #[doc(hidden)]
234 #[cfg(not(target_arch = "wasm32"))]
235 pub fn #handler(req: ::next_rust::Request) -> ::next_rust::BoxFuture<::next_rust::Response> {
236 ::std::boxed::Box::pin(#call)
237 }
238 }
239 .into()
240}
241
242#[proc_macro]
246pub fn action(input: TokenStream) -> TokenStream {
247 let mut path = parse_macro_input!(input as syn::Path);
248 let Some(last) = path.segments.last_mut() else { return error(Span::call_site(), "expected a function path") };
249 last.ident = format_ident!("__NR_ACTION_ID_{}", last.ident);
250 quote!(::next_rust::ActionRef::new(#path)).into()
251}
252
253fn read_relative(lit: &LitStr, base: &Path) -> Result<(PathBuf, String), TokenStream> {
258 let rel = lit.value();
259 let direct = base.join(&rel);
260 let path = if direct.is_file() {
261 direct
262 } else {
263 match find_unique(&search_roots(), Path::new(&rel)) {
267 Found::One(p) => p,
268 Found::Many(list) => {
269 let names: Vec<String> = list.iter().map(|p| p.display().to_string()).collect();
270 return Err(error(
271 lit.span(),
272 format!(
273 "`{rel}` matches several files; use a path relative to this source file:\n {}",
274 names.join("\n ")
275 ),
276 ));
277 }
278 Found::None => {
279 return Err(error(
280 lit.span(),
281 format!("cannot find `{rel}` (looked next to this file and in the project)"),
282 ));
283 }
284 }
285 };
286 match std::fs::read_to_string(&path) {
287 Ok(text) => Ok((path, text)),
288 Err(e) => Err(error(lit.span(), format!("cannot read {}: {e}", path.display()))),
289 }
290}
291
292enum Found {
293 None,
294 One(PathBuf),
295 Many(Vec<PathBuf>),
296}
297
298fn search_roots() -> Vec<PathBuf> {
300 let manifest = manifest_dir();
301 let mut roots = Vec::new();
302 let app = std::fs::read_to_string(manifest.join("next-rust.toml"))
303 .ok()
304 .and_then(|toml| configured_app_dir(&toml))
305 .unwrap_or_else(|| "app".to_owned());
306 roots.push(manifest.join(app));
307 roots.push(manifest);
308 roots
309}
310
311fn configured_app_dir(toml: &str) -> Option<String> {
313 let mut in_app = false;
314 for line in toml.lines() {
315 let line = line.split('#').next().unwrap_or("").trim();
316 if line.starts_with('[') {
317 in_app = line == "[app]";
318 } else if in_app && let Some(value) = line.strip_prefix("directory") {
319 let value = value.trim_start().strip_prefix('=')?.trim().trim_matches('"');
320 return Some(value.to_owned());
321 }
322 }
323 None
324}
325
326fn find_unique(roots: &[PathBuf], rel: &Path) -> Found {
329 for root in roots {
330 let mut matches = Vec::new();
331 collect_matches(root, rel, 0, &mut matches);
332 matches.sort();
333 matches.dedup();
334 match matches.len() {
335 0 => continue,
336 1 => return Found::One(matches.remove(0)),
337 _ => return Found::Many(matches),
338 }
339 }
340 Found::None
341}
342
343fn collect_matches(dir: &Path, rel: &Path, depth: usize, out: &mut Vec<PathBuf>) {
344 if depth > 12 || out.len() > 16 {
345 return;
346 }
347 let Ok(entries) = std::fs::read_dir(dir) else { return };
348 for entry in entries.flatten() {
349 let path = entry.path();
350 let name = entry.file_name();
351 let name = name.to_string_lossy();
352 let Ok(kind) = entry.file_type() else { continue };
353 if kind.is_dir() {
354 if !name.starts_with('.') && name != "target" && name != "node_modules" {
355 collect_matches(&path, rel, depth + 1, out);
356 }
357 } else if path.ends_with(rel) {
358 out.push(path);
359 }
360 }
361}
362
363fn field_ident(class: &str) -> Option<syn::Ident> {
364 let name: String = class.chars().map(|c| if c.is_ascii_alphanumeric() || c == '_' { c } else { '_' }).collect();
365 if name.is_empty() || name.starts_with(|c: char| c.is_ascii_digit()) {
366 return None;
367 }
368 syn::parse_str::<syn::Ident>(&name).ok().or_else(|| Some(syn::Ident::new_raw(&name, Span::call_site())))
369}
370
371#[proc_macro]
384pub fn css_module(input: TokenStream) -> TokenStream {
385 let lit = parse_macro_input!(input as LitStr);
386 let (path, text) = match read_relative(&lit, &caller_dir()) {
387 Ok(v) => v,
388 Err(e) => return e,
389 };
390 let salt = path.strip_prefix(manifest_dir()).unwrap_or(&path).to_string_lossy().replace('\\', "/");
391 let out = next_rust_assets::css::scope(&text, &salt, true);
392 let id = next_rust_assets::content_hash(out.css.as_bytes())[..12].to_owned();
393 let css = out.css;
394 let abs = path.to_string_lossy().into_owned();
395 let mut seen = std::collections::HashMap::new();
396 let mut fields = Vec::new();
397 let mut values = Vec::new();
398 for (class, scoped) in &out.classes {
399 let Some(ident) = field_ident(class) else {
400 return error(lit.span(), format!("class `{class}` cannot be used as a Rust field name"));
401 };
402 if let Some(prev) = seen.insert(ident.to_string(), class.clone()) {
403 return error(lit.span(), format!("classes `{prev}` and `{class}` map to the same field `{ident}`"));
404 }
405 fields.push(quote!(pub #ident: ::next_rust::CssClass));
406 values.push(quote!(#ident: ::next_rust::CssClass::new(#scoped, &__NR_SHEET)));
407 }
408 quote! {{
409 const _: &[u8] = include_bytes!(#abs);
410 static __NR_SHEET: ::next_rust::Stylesheet = ::next_rust::Stylesheet { id: #id, css: #css };
411 #[allow(non_camel_case_types, dead_code)]
412 #[derive(Clone, Copy)]
413 struct __NrCssModule { #(#fields,)* }
414 __NrCssModule { #(#values,)* }
415 }}
416 .into()
417}
418
419#[proc_macro]
423pub fn global_css(input: TokenStream) -> TokenStream {
424 let lit = parse_macro_input!(input as LitStr);
425 let (path, text) = match read_relative(&lit, &caller_dir()) {
426 Ok(v) => v,
427 Err(e) => return e,
428 };
429 let css = next_rust_assets::css::minify(&text);
430 let id = next_rust_assets::content_hash(css.as_bytes())[..12].to_owned();
431 let abs = path.to_string_lossy().into_owned();
432 quote! {{
433 const _: &[u8] = include_bytes!(#abs);
434 static __NR_SHEET: ::next_rust::Stylesheet = ::next_rust::Stylesheet { id: #id, css: #css };
435 &__NR_SHEET
436 }}
437 .into()
438}
439
440#[proc_macro]
445pub fn asset(input: TokenStream) -> TokenStream {
446 let lit = parse_macro_input!(input as LitStr);
447 let rel = lit.value();
448 let rel = rel.trim_start_matches('/');
449 if rel.split('/').any(|s| s == ".." || s.starts_with('.')) {
450 return error(lit.span(), "asset paths must stay inside assets/ and not reference hidden files");
451 }
452 let path = manifest_dir().join("assets").join(rel);
453 let bytes = match std::fs::read(&path) {
454 Ok(b) => b,
455 Err(e) => return error(lit.span(), format!("cannot read {}: {e}", path.display())),
456 };
457 let (dir, file) = match rel.rsplit_once('/') {
458 Some((d, f)) => (format!("{d}/"), f.to_owned()),
459 None => (String::new(), rel.to_owned()),
460 };
461 let url = format!("/_nr/assets/{dir}{}", next_rust_assets::fingerprint_name(&file, &bytes));
462 let abs = path.to_string_lossy().into_owned();
463 quote! {{
464 const _: &[u8] = include_bytes!(#abs);
465 #url
466 }}
467 .into()
468}
469
470#[cfg(test)]
471mod tests {
472 use super::*;
473
474 fn temp(name: &str) -> PathBuf {
475 let dir = std::env::temp_dir().join(format!("nr-macros-{name}-{}", std::process::id()));
476 let _ = std::fs::remove_dir_all(&dir);
477 dir
478 }
479
480 fn touch(path: PathBuf) {
481 std::fs::create_dir_all(path.parent().unwrap()).unwrap();
482 std::fs::write(path, "body{}").unwrap();
483 }
484
485 #[test]
486 fn finds_a_stylesheet_inside_the_app_directory() {
487 let root = temp("unique");
488 touch(root.join("app/globals.css"));
489 touch(root.join("target/debug/globals.css"));
490 let roots = vec![root.join("app"), root.clone()];
491 assert!(
492 matches!(find_unique(&roots, Path::new("globals.css")), Found::One(p) if p == root.join("app/globals.css"))
493 );
494 std::fs::remove_dir_all(root).unwrap();
495 }
496
497 #[test]
498 fn app_directory_wins_and_ambiguity_is_reported() {
499 let root = temp("many");
500 touch(root.join("app/a/card.css"));
501 touch(root.join("app/b/card.css"));
502 touch(root.join("styles/card.css"));
503 let roots = vec![root.join("app"), root.clone()];
504 assert!(matches!(find_unique(&roots, Path::new("card.css")), Found::Many(list) if list.len() == 2));
505 assert!(matches!(find_unique(&roots, Path::new("a/card.css")), Found::One(_)));
506 assert!(matches!(find_unique(&roots, Path::new("missing.css")), Found::None));
507 std::fs::remove_dir_all(root).unwrap();
508 }
509
510 #[test]
511 fn reads_the_configured_app_directory() {
512 assert_eq!(
513 configured_app_dir("[server]\nport = 1\n[app]\ndirectory = \"src/web\" # routes\n").as_deref(),
514 Some("src/web")
515 );
516 assert_eq!(configured_app_dir("[build]\ndirectory = \"x\"\n"), None);
517 }
518}