| 
 | 1 | +// This file is Copyright its original authors, visible in version control  | 
 | 2 | +// history.  | 
 | 3 | +//  | 
 | 4 | +// This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE  | 
 | 5 | +// or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license  | 
 | 6 | +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.  | 
 | 7 | +// You may not use this file except in accordance with one or both of these  | 
 | 8 | +// licenses.  | 
 | 9 | + | 
 | 10 | +#![crate_name = "lightning_macros"]  | 
 | 11 | + | 
 | 12 | +//! Proc macros used by LDK  | 
 | 13 | +
  | 
 | 14 | +#![cfg_attr(not(test), no_std)]  | 
 | 15 | +#![deny(missing_docs)]  | 
 | 16 | +#![forbid(unsafe_code)]  | 
 | 17 | +#![deny(rustdoc::broken_intra_doc_links)]  | 
 | 18 | +#![deny(rustdoc::private_intra_doc_links)]  | 
 | 19 | +#![cfg_attr(docsrs, feature(doc_auto_cfg))]  | 
 | 20 | + | 
 | 21 | +use proc_macro::TokenStream;  | 
 | 22 | +use quote::quote;  | 
 | 23 | +use syn::spanned::Spanned;  | 
 | 24 | +use syn::{parse, ImplItemFn, Token};  | 
 | 25 | + | 
 | 26 | +fn add_async_method(mut parsed: ImplItemFn) -> TokenStream {  | 
 | 27 | +	let output = quote! {  | 
 | 28 | +		#[cfg(not(feature = "async-interface"))]  | 
 | 29 | +		#parsed  | 
 | 30 | +	};  | 
 | 31 | + | 
 | 32 | +	parsed.sig.asyncness = Some(Token));  | 
 | 33 | + | 
 | 34 | +	let output = quote! {  | 
 | 35 | +		#output  | 
 | 36 | + | 
 | 37 | +		#[cfg(feature = "async-interface")]  | 
 | 38 | +		#parsed  | 
 | 39 | +	};  | 
 | 40 | + | 
 | 41 | +	output.into()  | 
 | 42 | +}  | 
 | 43 | + | 
 | 44 | +/// Makes a method `async`, if the `async-interface` feature is enabled.  | 
 | 45 | +#[proc_macro_attribute]  | 
 | 46 | +pub fn maybe_async(_attr: TokenStream, item: TokenStream) -> TokenStream {  | 
 | 47 | +	if let Ok(parsed) = parse(item) {  | 
 | 48 | +		add_async_method(parsed)  | 
 | 49 | +	} else {  | 
 | 50 | +		(quote! {  | 
 | 51 | +			compile_error!("#[maybe_async] can only be used on methods")  | 
 | 52 | +		})  | 
 | 53 | +		.into()  | 
 | 54 | +	}  | 
 | 55 | +}  | 
 | 56 | + | 
 | 57 | +/// Awaits, if the `async-interface` feature is enabled.  | 
 | 58 | +#[proc_macro]  | 
 | 59 | +pub fn maybe_await(expr: TokenStream) -> TokenStream {  | 
 | 60 | +	let expr: proc_macro2::TokenStream = expr.into();  | 
 | 61 | +	let quoted = quote! {  | 
 | 62 | +		{  | 
 | 63 | +			#[cfg(not(feature = "async-interface"))]  | 
 | 64 | +			{  | 
 | 65 | +				#expr  | 
 | 66 | +			}  | 
 | 67 | + | 
 | 68 | +			#[cfg(feature = "async-interface")]  | 
 | 69 | +			{  | 
 | 70 | +				#expr.await  | 
 | 71 | +			}  | 
 | 72 | +		}  | 
 | 73 | +	};  | 
 | 74 | + | 
 | 75 | +	quoted.into()  | 
 | 76 | +}  | 
0 commit comments