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 usage = CssUsage::load();
392 let text = match &usage {
393 Some(u) => next_rust_assets::css::prune(&next_rust_assets::css::minify(&text), &|name| {
395 u.names.contains(name) || u.names.contains(&name.replace('-', "_"))
396 }),
397 None => text,
398 };
399 let track = usage.as_ref().map(CssUsage::track);
400 let out = next_rust_assets::css::scope(&text, &salt, true);
401 let id = next_rust_assets::content_hash(out.css.as_bytes())[..12].to_owned();
402 let css = out.css;
403 let abs = path.to_string_lossy().into_owned();
404 let mut seen = std::collections::HashMap::new();
405 let mut fields = Vec::new();
406 let mut values = Vec::new();
407 for (class, scoped) in &out.classes {
408 let Some(ident) = field_ident(class) else {
409 return error(lit.span(), format!("class `{class}` cannot be used as a Rust field name"));
410 };
411 if let Some(prev) = seen.insert(ident.to_string(), class.clone()) {
412 return error(lit.span(), format!("classes `{prev}` and `{class}` map to the same field `{ident}`"));
413 }
414 fields.push(quote!(pub #ident: ::next_rust::CssClass));
415 values.push(quote!(#ident: ::next_rust::CssClass::new(#scoped, &__NR_SHEET)));
416 }
417 quote! {{
418 const _: &[u8] = include_bytes!(#abs);
419 #track
420 static __NR_SHEET: ::next_rust::Stylesheet = ::next_rust::Stylesheet { id: #id, css: #css };
421 #[allow(non_camel_case_types, dead_code)]
422 #[derive(Clone, Copy)]
423 struct __NrCssModule { #(#fields,)* }
424 __NrCssModule { #(#values,)* }
425 }}
426 .into()
427}
428
429#[proc_macro]
433pub fn global_css(input: TokenStream) -> TokenStream {
434 let lit = parse_macro_input!(input as LitStr);
435 let (path, text) = match read_relative(&lit, &caller_dir()) {
436 Ok(v) => v,
437 Err(e) => return e,
438 };
439 let css = next_rust_assets::css::minify(&text);
440 let usage = CssUsage::load();
441 let css = match &usage {
442 Some(u) => next_rust_assets::css::prune(&css, &|name| u.names.contains(name)),
443 None => css,
444 };
445 let track = usage.as_ref().map(CssUsage::track);
446 let id = next_rust_assets::content_hash(css.as_bytes())[..12].to_owned();
447 let abs = path.to_string_lossy().into_owned();
448 quote! {{
449 const _: &[u8] = include_bytes!(#abs);
450 #track
451 static __NR_SHEET: ::next_rust::Stylesheet = ::next_rust::Stylesheet { id: #id, css: #css };
452 &__NR_SHEET
453 }}
454 .into()
455}
456
457struct CssUsage {
461 names: std::collections::HashSet<String>,
462 file: String,
463}
464
465impl CssUsage {
466 fn load() -> Option<Self> {
467 let file = PathBuf::from(std::env::var_os("OUT_DIR")?).join("next_rust_css_usage.txt");
468 let text = std::fs::read_to_string(&file).ok()?;
469 Some(CssUsage { names: text.lines().map(str::to_owned).collect(), file: file.to_string_lossy().into_owned() })
470 }
471
472 fn track(&self) -> proc_macro2::TokenStream {
474 let file = &self.file;
475 quote!(
476 const _: &[u8] = include_bytes!(#file);
477 )
478 }
479}
480
481#[proc_macro]
486pub fn asset(input: TokenStream) -> TokenStream {
487 let lit = parse_macro_input!(input as LitStr);
488 let rel = lit.value();
489 let rel = rel.trim_start_matches('/');
490 if rel.split('/').any(|s| s == ".." || s.starts_with('.')) {
491 return error(lit.span(), "asset paths must stay inside assets/ and not reference hidden files");
492 }
493 let path = manifest_dir().join("assets").join(rel);
494 let bytes = match std::fs::read(&path) {
495 Ok(b) => b,
496 Err(e) => return error(lit.span(), format!("cannot read {}: {e}", path.display())),
497 };
498 let (dir, file) = match rel.rsplit_once('/') {
499 Some((d, f)) => (format!("{d}/"), f.to_owned()),
500 None => (String::new(), rel.to_owned()),
501 };
502 let url = format!("/_nr/assets/{dir}{}", next_rust_assets::fingerprint_name(&file, &bytes));
503 let abs = path.to_string_lossy().into_owned();
504 quote! {{
505 const _: &[u8] = include_bytes!(#abs);
506 #url
507 }}
508 .into()
509}
510
511#[cfg(test)]
512mod tests {
513 use super::*;
514
515 fn temp(name: &str) -> PathBuf {
516 let dir = std::env::temp_dir().join(format!("nr-macros-{name}-{}", std::process::id()));
517 let _ = std::fs::remove_dir_all(&dir);
518 dir
519 }
520
521 fn touch(path: PathBuf) {
522 std::fs::create_dir_all(path.parent().unwrap()).unwrap();
523 std::fs::write(path, "body{}").unwrap();
524 }
525
526 #[test]
527 fn finds_a_stylesheet_inside_the_app_directory() {
528 let root = temp("unique");
529 touch(root.join("app/globals.css"));
530 touch(root.join("target/debug/globals.css"));
531 let roots = vec![root.join("app"), root.clone()];
532 assert!(
533 matches!(find_unique(&roots, Path::new("globals.css")), Found::One(p) if p == root.join("app/globals.css"))
534 );
535 std::fs::remove_dir_all(root).unwrap();
536 }
537
538 #[test]
539 fn app_directory_wins_and_ambiguity_is_reported() {
540 let root = temp("many");
541 touch(root.join("app/a/card.css"));
542 touch(root.join("app/b/card.css"));
543 touch(root.join("styles/card.css"));
544 let roots = vec![root.join("app"), root.clone()];
545 assert!(matches!(find_unique(&roots, Path::new("card.css")), Found::Many(list) if list.len() == 2));
546 assert!(matches!(find_unique(&roots, Path::new("a/card.css")), Found::One(_)));
547 assert!(matches!(find_unique(&roots, Path::new("missing.css")), Found::None));
548 std::fs::remove_dir_all(root).unwrap();
549 }
550
551 #[test]
552 fn reads_the_configured_app_directory() {
553 assert_eq!(
554 configured_app_dir("[server]\nport = 1\n[app]\ndirectory = \"src/web\" # routes\n").as_deref(),
555 Some("src/web")
556 );
557 assert_eq!(configured_app_dir("[build]\ndirectory = \"x\"\n"), None);
558 }
559}