1use proc_macro::TokenStream;
4use proc_macro2::TokenStream as TokenStream2;
5use quote::{format_ident, quote, quote_spanned};
6use syn::ext::IdentExt;
7use syn::parse::{Parse, ParseStream};
8use syn::spanned::Spanned;
9use syn::visit::Visit;
10use syn::{
11 FnArg, GenericArgument, GenericParam, Ident, ItemTrait, LitBool, Pat, Path, PathArguments, ReturnType, Signature,
12 Token, TraitItem, TraitItemFn, Type, TypeParamBound, WherePredicate, parse_quote,
13};
14
15const RESERVED: &[&str] = &[
17 "get_facade_accessor",
18 "get_facade_root",
19 "try_get_facade_root",
20 "swap",
21 "is_fake",
22 "clear_resolved_instance",
23 "resolved",
24 "fake",
25 "should_receive",
26 "expects",
27];
28
29#[proc_macro_attribute]
169pub fn extends_facade(attr: TokenStream, item: TokenStream) -> TokenStream {
170 expand_attribute(attr.into(), item.into()).into()
171}
172
173fn expand_attribute(attr: TokenStream2, item: TokenStream2) -> TokenStream2 {
176 let item: ItemTrait = match syn::parse2(item) {
177 Ok(item) => item,
178 Err(e) => return e.into_compile_error(),
179 };
180 let expanded = syn::parse2::<Args>(attr)
182 .and_then(|args| expand(&args, &item))
183 .unwrap_or_else(syn::Error::into_compile_error);
184 quote! {
185 #item
186 #expanded
187 }
188}
189
190struct Args {
191 name: Ident,
192 cached: bool,
193 krate: Path,
194}
195
196impl Parse for Args {
197 fn parse(input: ParseStream) -> syn::Result<Self> {
198 let mut args = Args {
199 name: input.parse()?,
200 cached: true,
201 krate: parse_quote!(::laravel_facade),
202 };
203 while !input.is_empty() {
204 input.parse::<Token![,]>()?;
205 if input.is_empty() {
206 break;
207 }
208 let key = input.call(Ident::parse_any)?;
209 input.parse::<Token![=]>()?;
210 match key.to_string().as_str() {
211 "cached" => args.cached = input.parse::<LitBool>()?.value,
212 "crate" => args.krate = input.parse()?,
213 _ => {
214 return Err(syn::Error::new(
215 key.span(),
216 "unknown option; expected `cached` or `crate`",
217 ));
218 }
219 }
220 }
221 Ok(args)
222 }
223}
224
225fn expand(args: &Args, item: &ItemTrait) -> syn::Result<TokenStream2> {
226 let Args { name, cached, krate } = args;
227 let vis = &item.vis;
228 let tr = &item.ident;
229
230 if !item.generics.params.is_empty() {
231 return Err(syn::Error::new(
232 item.generics.lt_token.unwrap_or_default().span,
233 "#[extends_facade] does not support generic traits",
234 ));
235 }
236
237 let mut errors: Option<syn::Error> = None;
238 let mut methods = Vec::new();
239 for trait_item in &item.items {
240 let TraitItem::Fn(f) = trait_item else { continue };
241 match forward(tr, krate, vis, f) {
242 Ok(Some(method)) => methods.push(method),
243 Ok(None) => {}
244 Err(e) => match &mut errors {
245 Some(errors) => errors.combine(e),
246 None => errors = Some(e),
247 },
248 }
249 }
250 if let Some(errors) = errors {
251 return Err(errors);
252 }
253
254 let doc = format!("Facade for [`{tr}`]. Generated by `#[extends_facade]`.");
255 Ok(quote! {
256 #[doc = #doc]
257 #[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
258 #vis struct #name;
259
260 impl #krate::ExtendsFacade for #name {
261 type Accessor = dyn #tr;
262 const CACHED: bool = #cached;
263 }
264
265 #[allow(dead_code)]
266 impl #name {
267 #vis fn get_facade_accessor() -> &'static str {
269 <Self as #krate::ExtendsFacade>::get_facade_accessor()
270 }
271
272 #vis fn get_facade_root() -> ::std::sync::Arc<dyn #tr> {
274 <Self as #krate::ExtendsFacade>::get_facade_root()
275 }
276
277 #vis fn try_get_facade_root() -> ::core::result::Result<::std::sync::Arc<dyn #tr>, #krate::Error> {
279 <Self as #krate::ExtendsFacade>::try_get_facade_root()
280 }
281
282 #vis fn swap(instance: ::std::sync::Arc<dyn #tr>) {
284 <Self as #krate::ExtendsFacade>::swap(instance)
285 }
286
287 #vis fn is_fake() -> bool {
289 <Self as #krate::ExtendsFacade>::is_fake()
290 }
291
292 #vis fn clear_resolved_instance() {
294 <Self as #krate::ExtendsFacade>::clear_resolved_instance()
295 }
296
297 #vis fn resolved(
299 callback: impl Fn(&::std::sync::Arc<dyn #tr>, &#krate::Application) + Send + Sync + 'static,
300 ) {
301 <Self as #krate::ExtendsFacade>::resolved(callback)
302 }
303
304 #vis fn fake<__FacadeFake: #tr + #krate::Fake>(fake: __FacadeFake) -> ::std::sync::Arc<__FacadeFake> {
307 let fake = ::std::sync::Arc::new(fake);
308 #krate::__private::fake::<Self>(::std::sync::Arc::clone(&fake) as ::std::sync::Arc<dyn #tr>);
309 fake
310 }
311
312 #vis fn should_receive<__FacadeMock: #tr + ::core::default::Default, __FacadeR>(
317 expect: impl ::core::ops::FnOnce(&mut __FacadeMock) -> __FacadeR,
318 ) -> __FacadeR {
319 #krate::__private::should_receive::<Self, __FacadeMock, __FacadeR>(
320 |mock| -> ::std::sync::Arc<dyn #tr> { mock },
321 expect,
322 )
323 }
324
325 #vis fn expects<__FacadeMock: #tr + ::core::default::Default, __FacadeR>(
327 expect: impl ::core::ops::FnOnce(&mut __FacadeMock) -> __FacadeR,
328 ) -> __FacadeR {
329 Self::should_receive(expect)
330 }
331
332 #(#methods)*
333 }
334 })
335}
336
337enum Receiver {
338 Ref,
340 Arc,
342}
343
344fn forward(tr: &Ident, krate: &Path, vis: &syn::Visibility, f: &TraitItemFn) -> syn::Result<Option<TokenStream2>> {
346 let sig = &f.sig;
347 let ident = &sig.ident;
348
349 if requires_sized_self(sig) {
351 return Ok(None);
352 }
353 let Some(receiver) = sig.receiver() else {
354 return Ok(None);
355 };
356 if sig
357 .generics
358 .params
359 .iter()
360 .any(|p| !matches!(p, GenericParam::Lifetime(_)))
361 {
362 return Ok(None);
363 }
364
365 if RESERVED.contains(&ident.to_string().as_str()) {
366 return Err(syn::Error::new(
367 ident.span(),
368 format!("`{ident}` clashes with a method generated on every facade"),
369 ));
370 }
371 if sig.generics.lifetimes().any(|l| l.lifetime.ident == "async_trait") {
372 return Err(syn::Error::new(
373 ident.span(),
374 "#[extends_facade] must be placed above #[async_trait]",
375 ));
376 }
377
378 let kind = if receiver.colon_token.is_none() {
379 match (&receiver.reference, &receiver.mutability) {
380 (Some(_), None) => Receiver::Ref,
381 (Some(_), Some(_)) => {
382 return Err(syn::Error::new(
383 receiver.self_token.span,
384 "#[extends_facade] cannot forward `&mut self` methods: the facade root is shared behind `Arc`",
385 ));
386 }
387 _ => {
388 return Err(syn::Error::new(
389 receiver.self_token.span,
390 "#[extends_facade] cannot forward `self` methods; add `where Self: Sized` to skip it",
391 ));
392 }
393 }
394 } else if is_arc_self(&receiver.ty) {
395 Receiver::Arc
396 } else if matches!(&*receiver.ty, Type::Reference(r) if r.mutability.is_none() && is_self(&r.elem)) {
397 Receiver::Ref
398 } else {
399 return Err(syn::Error::new(
400 receiver.self_token.span,
401 "#[extends_facade] can only forward `&self` and `self: Arc<Self>` methods",
402 ));
403 };
404
405 if let ReturnType::Type(_, ty) = &sig.output {
406 let mut finder = ElidedLifetime(None);
407 finder.visit_type(ty);
408 if let Some(span) = finder.0 {
409 return Err(syn::Error::new(
410 span,
411 "#[extends_facade] cannot forward a method that returns a borrow of `self`; return an owned value or name the lifetime of an argument",
412 ));
413 }
414 }
415
416 let mut static_sig: Signature = sig.clone();
418 static_sig.inputs = Default::default();
419 let mut arg_names = Vec::new();
420 for (i, input) in sig.inputs.iter().enumerate() {
421 let FnArg::Typed(pat_type) = input else { continue };
422 let name = match &*pat_type.pat {
423 Pat::Ident(p) if p.ident != "self" => p.ident.clone(),
424 _ => format_ident!("__arg{i}"),
425 };
426 let ty = &pat_type.ty;
427 static_sig.inputs.push(parse_quote!(#name: #ty));
428 arg_names.push(name);
429 }
430
431 let root = quote!(<Self as #krate::ExtendsFacade>::get_facade_root());
432 let target = quote!(<dyn #tr as #tr>::#ident);
433 let mut call = match kind {
434 Receiver::Ref => quote!(#target(&*__facade_root #(, #arg_names)*)),
435 Receiver::Arc => quote!(#target(__facade_root #(, #arg_names)*)),
436 };
437 if sig.asyncness.is_some() {
438 call = quote!(#call.await);
439 }
440 if sig.unsafety.is_some() {
441 call = quote!(unsafe { #call });
442 }
443
444 let attrs = f.attrs.iter().filter(|a| {
445 ["doc", "cfg", "deprecated", "must_use", "allow", "expect"]
446 .iter()
447 .any(|name| a.path().is_ident(name))
448 });
449
450 Ok(Some(quote_spanned! {sig.span()=>
451 #(#attrs)*
452 #vis #static_sig {
453 let __facade_root = #root;
454 #call
455 }
456 }))
457}
458
459fn requires_sized_self(sig: &Signature) -> bool {
460 let Some(where_clause) = &sig.generics.where_clause else {
461 return false;
462 };
463 where_clause.predicates.iter().any(|p| {
464 let WherePredicate::Type(p) = p else { return false };
465 is_self(&p.bounded_ty)
466 && p.bounds
467 .iter()
468 .any(|b| matches!(b, TypeParamBound::Trait(t) if t.path.is_ident("Sized")))
469 })
470}
471
472fn is_self(ty: &Type) -> bool {
473 matches!(ty, Type::Path(p) if p.qself.is_none() && p.path.is_ident("Self"))
474}
475
476fn is_arc_self(ty: &Type) -> bool {
477 let Type::Path(p) = ty else { return false };
478 p.path.segments.last().is_some_and(|last| {
479 last.ident == "Arc"
480 && matches!(
481 &last.arguments,
482 PathArguments::AngleBracketed(args)
483 if matches!(args.args.first(), Some(GenericArgument::Type(ty)) if is_self(ty))
484 )
485 })
486}
487
488struct ElidedLifetime(Option<proc_macro2::Span>);
490
491impl<'ast> Visit<'ast> for ElidedLifetime {
492 fn visit_type_reference(&mut self, r: &'ast syn::TypeReference) {
493 if r.lifetime.is_none() && self.0.is_none() {
494 self.0 = Some(r.and_token.span);
495 }
496 syn::visit::visit_type_reference(self, r);
497 }
498
499 fn visit_lifetime(&mut self, l: &'ast syn::Lifetime) {
500 if l.ident == "_" && self.0.is_none() {
501 self.0 = Some(l.span());
502 }
503 }
504
505 fn visit_type_bare_fn(&mut self, _: &'ast syn::TypeBareFn) {}
507 fn visit_parenthesized_generic_arguments(&mut self, _: &'ast syn::ParenthesizedGenericArguments) {}
508}
509
510#[cfg(test)]
511mod tests {
512 use super::*;
513
514 fn expand(attr: &str, item: &str) -> String {
515 expand_attribute(attr.parse().unwrap(), item.parse().unwrap()).to_string()
516 }
517
518 fn expand_method(method: &str) -> String {
520 expand("F", &format!("pub trait T: Interface {{ {method} }}"))
521 }
522
523 #[track_caller]
524 fn assert_error(output: &str, message: &str) {
525 assert!(output.contains("compile_error"), "no error in: {output}");
526 assert!(output.contains(message), "no `{message}` in: {output}");
527 }
528
529 #[track_caller]
530 fn assert_no_error(output: &str) {
531 assert!(!output.contains("compile_error"), "unexpected error in: {output}");
532 }
533
534 fn has_static_method(output: &str, name: &str) -> bool {
536 let generated = &output[output.find("impl F {").unwrap()..];
537 generated.contains(&format!("fn {name} (")) || generated.contains(&format!("fn {name} <"))
538 }
539
540 #[test]
541 fn generates_the_facade() {
542 let output = expand(
543 "Cache",
544 "pub trait CacheStore: Interface { fn get(&self, key: &str) -> Option<String>; }",
545 );
546 assert_no_error(&output);
547 assert!(output.contains("pub trait CacheStore"));
548 assert!(output.contains("pub struct Cache ;"));
549 assert!(output.contains("Facade for [`CacheStore`]. Generated by `#[extends_facade]`."));
550 assert!(output.contains("impl :: laravel_facade :: ExtendsFacade for Cache"));
551 assert!(output.contains("type Accessor = dyn CacheStore"));
552 assert!(output.contains("const CACHED : bool = true"));
553 assert!(output.contains("pub fn get (key : & str) -> Option < String >"));
554 assert!(output.contains("< dyn CacheStore as CacheStore > :: get (& * __facade_root , key)"));
555 for name in RESERVED {
556 assert!(output.contains(&format!("fn {name}")), "missing {name}");
557 }
558 }
559
560 #[test]
561 fn keeps_the_visibility_of_the_trait() {
562 let output = expand("F", "pub(crate) trait T: Interface { fn f(&self); }");
563 assert!(output.contains("pub (crate) struct F ;"));
564 assert!(output.contains("pub (crate) fn f ()"));
565
566 let output = expand("F", "trait T: Interface { fn f(&self); }");
567 assert!(output.contains("struct F ;"));
568 assert!(!output.contains("pub"));
569 }
570
571 #[test]
572 fn parses_options() {
573 let output = expand("F, cached = false, crate = ::my::facade,", "trait T: Interface {}");
574 assert_no_error(&output);
575 assert!(output.contains("const CACHED : bool = false"));
576 assert!(output.contains("impl :: my :: facade :: ExtendsFacade for F"));
577 assert!(!output.contains("laravel_facade"));
578
579 assert_no_error(&expand("F,", "trait T: Interface {}"));
580 }
581
582 #[test]
583 fn rejects_bad_options() {
584 let item = "trait T: Interface {}";
585 assert_error(
586 &expand("F, cache = false", item),
587 "unknown option; expected `cached` or `crate`",
588 );
589 assert_error(&expand("F, cached = 1", item), "expected boolean literal");
590 assert_error(&expand("F, cached", item), "expected `=`");
591 assert_error(&expand("F cached", item), "expected `,`");
592 assert_error(&expand("F, 1 = 2", item), "expected ident");
593 assert_error(&expand("F, crate = 1", item), "expected identifier");
594 assert_error(&expand("", item), "expected identifier");
595 assert!(expand("", item).contains("trait T"));
597 }
598
599 #[test]
600 fn rejects_non_traits() {
601 assert_error(&expand("F", "struct S;"), "expected `trait`");
602 }
603
604 #[test]
605 fn rejects_generic_traits() {
606 assert_error(
607 &expand("F", "trait T<U>: Interface {}"),
608 "does not support generic traits",
609 );
610 assert_error(
611 &expand("F", "trait T<'a>: Interface {}"),
612 "does not support generic traits",
613 );
614 }
615
616 #[test]
617 fn forwards_supported_receivers() {
618 for (method, call) in [
619 ("fn f(&self);", "(& * __facade_root)"),
620 ("fn f(self: &Self);", "(& * __facade_root)"),
621 ("fn f(self: Arc<Self>);", "(__facade_root)"),
622 ("fn f(self: std::sync::Arc<Self>);", "(__facade_root)"),
623 ] {
624 let output = expand_method(method);
625 assert_no_error(&output);
626 assert!(
627 output.contains(&format!("< dyn T as T > :: f {call}")),
628 "{method}: {output}"
629 );
630 }
631 }
632
633 #[test]
634 fn rejects_unsupported_receivers() {
635 for (method, message) in [
636 ("fn f(&mut self);", "cannot forward `&mut self` methods"),
637 (
638 "fn f(self);",
639 "cannot forward `self` methods; add `where Self: Sized` to skip it",
640 ),
641 ("fn f(mut self);", "cannot forward `self` methods"),
642 (
643 "fn f(self: Box<Self>);",
644 "can only forward `&self` and `self: Arc<Self>` methods",
645 ),
646 ("fn f(self: &mut Self);", "can only forward"),
647 ("fn f(self: Arc<Box<Self>>);", "can only forward"),
648 ("fn f(self: Arc<'static, Self>);", "can only forward"),
649 ("fn f(self: Arc);", "can only forward"),
650 ("fn f(self: (Self,));", "can only forward"),
651 ("fn f(self: <Self as X>::Y);", "can only forward"),
652 ] {
653 assert_error(&expand_method(method), message);
654 }
655 }
656
657 #[test]
658 fn skips_methods_not_callable_on_dyn() {
659 for method in [
660 "fn new() -> Self where Self: Sized;",
661 "fn f(self) where Self: Sized;",
662 "fn f(&mut self) where Self: core::marker::Copy + Sized;",
663 "fn f<U>(&self, u: U);",
664 "fn f<const N: usize>(&self);",
665 "fn assoc();",
666 "const C: u8;",
667 "type X;",
668 ] {
669 let output = expand_method(method);
670 assert_no_error(&output);
671 assert!(
672 !has_static_method(&output, "f") && !has_static_method(&output, "new"),
673 "{method}: {output}"
674 );
675 }
676 }
677
678 #[test]
679 fn forwards_methods_with_other_where_clauses() {
680 for method in [
681 "fn f(&self) where Self: Clone;",
682 "fn f<'a, 'b>(&self, x: &'a str) where 'a: 'b;",
683 "fn f(&self) where Self: 'static;",
684 "fn f(&self) where u8: Sized;",
685 ] {
686 let output = expand_method(method);
687 assert_no_error(&output);
688 assert!(has_static_method(&output, "f"), "{method}: {output}");
689 }
690 }
691
692 #[test]
693 fn forwards_async_and_unsafe_methods() {
694 let output = expand_method("async fn f(&self) -> u8;");
695 assert!(output.contains("pub async fn f () -> u8"));
696 assert!(output.contains(":: f (& * __facade_root) . await"));
697
698 let output = expand_method("unsafe fn f(&self);");
699 assert!(output.contains("pub unsafe fn f ()"));
700 assert!(output.contains("unsafe { < dyn T as T > :: f (& * __facade_root) }"));
701
702 let output = expand_method("async unsafe fn f(&self);");
703 assert!(output.contains("unsafe { < dyn T as T > :: f (& * __facade_root) . await }"));
704 }
705
706 #[test]
707 fn rejects_async_trait_output() {
708 let method = "fn get<'life0, 'async_trait>(&'life0 self) -> Pin<Box<dyn Future<Output = String> + Send + 'async_trait>> where 'life0: 'async_trait, Self: 'async_trait;";
709 assert_error(&expand_method(method), "must be placed above #[async_trait]");
710 }
711
712 #[test]
713 fn rejects_reserved_names() {
714 for name in RESERVED {
715 assert_error(
716 &expand_method(&format!("fn {name}(&self);")),
717 &format!("`{name}` clashes with a method generated on every facade"),
718 );
719 }
720 }
721
722 #[test]
723 fn rejects_borrows_of_self_in_the_return_type() {
724 for method in [
725 "fn f(&self) -> &str;",
726 "fn f(&self) -> Option<&str>;",
727 "fn f(&self) -> Cow<'_, str>;",
728 "fn f(&self) -> (u8, &[u8]);",
729 "fn f(&self) -> &'static &str;",
730 ] {
731 assert_error(
732 &expand_method(method),
733 "cannot forward a method that returns a borrow of `self`",
734 );
735 }
736 }
737
738 #[test]
739 fn allows_returns_with_their_own_lifetimes() {
740 for method in [
741 "fn f<'a>(&self, x: &'a str) -> &'a str;",
742 "fn f(&self) -> &'static str;",
743 "fn f(&self) -> fn(&str) -> &str;",
744 "fn f(&self) -> Box<dyn Fn(&str) -> &str>;",
745 "fn f(&self) -> Box<dyn for<'a> Fn(&'a str) -> &'a str>;",
746 "fn f(&self);",
747 ] {
748 let output = expand_method(method);
749 assert_no_error(&output);
750 assert!(has_static_method(&output, "f"), "{method}: {output}");
751 }
752 }
753
754 #[test]
755 fn renames_argument_patterns() {
756 let output = expand_method("fn f(&self, key: &str, _: u8, mut count: u8, (a, b): (u8, u8)) {}");
757 assert_no_error(&output);
758 assert!(output.contains("fn f (key : & str , __arg2 : u8 , count : u8 , __arg4 : (u8 , u8))"));
759 assert!(output.contains(":: f (& * __facade_root , key , __arg2 , count , __arg4)"));
760 }
761
762 #[test]
763 fn copies_documentation_attributes_only() {
764 let output = expand_method(
765 "/// Docs.\n#[cfg(unix)] #[deprecated] #[must_use] #[allow(unused)] #[expect(dead_code)] #[inline] fn f(&self) -> u8;",
766 );
767 let generated = &output[output.find("impl F {").unwrap()..];
768 for attr in [
769 "doc = \" Docs.\"",
770 "cfg (unix)",
771 "deprecated",
772 "must_use",
773 "allow (unused)",
774 "expect (dead_code)",
775 ] {
776 assert!(generated.contains(attr), "missing {attr}: {generated}");
777 }
778 assert!(!generated.contains("inline"));
779 }
780
781 #[test]
782 fn combines_errors_from_several_methods() {
783 let output = expand_method("fn a(&mut self); fn b(&self) -> &str; fn swap(&self);");
784 assert_error(&output, "cannot forward `&mut self` methods");
785 assert_error(&output, "returns a borrow of `self`");
786 assert_error(&output, "`swap` clashes");
787 assert!(!output.contains("struct F"));
788 }
789}