use proc_macro::TokenStream;
use proc_macro2::{Literal, Span, TokenStream as TokenStream2};
use quote::{quote, ToTokens};
use syn::{parse_quote, punctuated::Punctuated, spanned::Spanned, token::Comma, FnArg, Ident};
#[proc_macro_attribute]
pub fn unstable_hostfn(_attr: TokenStream, item: TokenStream) -> TokenStream {
let input = syn::parse_macro_input!(item as syn::Item);
let expanded = quote! {
#[cfg(feature = "unstable-hostfn")]
#[cfg_attr(docsrs, doc(cfg(feature = "unstable-hostfn")))]
#input
};
expanded.into()
}
#[proc_macro_attribute]
pub fn define_env(attr: TokenStream, item: TokenStream) -> TokenStream {
if !attr.is_empty() {
let msg = r#"Invalid `define_env` attribute macro: expected no attributes:
- `#[define_env]`"#;
let span = TokenStream2::from(attr).span();
return syn::Error::new(span, msg).to_compile_error().into()
}
let item = syn::parse_macro_input!(item as syn::ItemMod);
match EnvDef::try_from(item) {
Ok(mut def) => expand_env(&mut def).into(),
Err(e) => e.to_compile_error().into(),
}
}
struct EnvDef {
host_funcs: Vec<HostFn>,
}
struct HostFn {
item: syn::ItemFn,
is_stable: bool,
name: String,
returns: HostFnReturn,
cfg: Option<syn::Attribute>,
}
enum HostFnReturn {
Unit,
U32,
U64,
ReturnCode,
}
impl HostFnReturn {
fn map_output(&self) -> TokenStream2 {
match self {
Self::Unit => quote! { |_| None },
_ => quote! { |ret_val| Some(ret_val.into()) },
}
}
fn success_type(&self) -> syn::ReturnType {
match self {
Self::Unit => syn::ReturnType::Default,
Self::U32 => parse_quote! { -> u32 },
Self::U64 => parse_quote! { -> u64 },
Self::ReturnCode => parse_quote! { -> ReturnErrorCode },
}
}
}
impl EnvDef {
pub fn try_from(item: syn::ItemMod) -> syn::Result<Self> {
let span = item.span();
let err = |msg| syn::Error::new(span, msg);
let items = &item
.content
.as_ref()
.ok_or(err("Invalid environment definition, expected `mod` to be inlined."))?
.1;
let extract_fn = |i: &syn::Item| match i {
syn::Item::Fn(i_fn) => Some(i_fn.clone()),
_ => None,
};
let host_funcs = items
.iter()
.filter_map(extract_fn)
.map(HostFn::try_from)
.collect::<Result<Vec<_>, _>>()?;
Ok(Self { host_funcs })
}
}
impl HostFn {
pub fn try_from(mut item: syn::ItemFn) -> syn::Result<Self> {
let err = |span, msg| {
let msg = format!("Invalid host function definition.\n{}", msg);
syn::Error::new(span, msg)
};
let msg = "Only #[stable], #[cfg] and #[mutating] attributes are allowed.";
let span = item.span();
let mut attrs = item.attrs.clone();
attrs.retain(|a| !a.path().is_ident("doc"));
let mut is_stable = false;
let mut mutating = false;
let mut cfg = None;
while let Some(attr) = attrs.pop() {
let ident = attr.path().get_ident().ok_or(err(span, msg))?.to_string();
match ident.as_str() {
"stable" => {
if is_stable {
return Err(err(span, "#[stable] can only be specified once"))
}
is_stable = true;
},
"mutating" => {
if mutating {
return Err(err(span, "#[mutating] can only be specified once"))
}
mutating = true;
},
"cfg" => {
if cfg.is_some() {
return Err(err(span, "#[cfg] can only be specified once"))
}
cfg = Some(attr);
},
id => return Err(err(span, &format!("Unsupported attribute \"{id}\". {msg}"))),
}
}
if mutating {
let stmt = syn::parse_quote! {
if self.ext().is_read_only() {
return Err(Error::<E::T>::StateChangeDenied.into());
}
};
item.block.stmts.insert(0, stmt);
}
let name = item.sig.ident.to_string();
let msg = "Every function must start with these two parameters: &mut self, memory: &mut M";
let special_args = item
.sig
.inputs
.iter()
.take(2)
.enumerate()
.map(|(i, arg)| is_valid_special_arg(i, arg))
.fold(0u32, |acc, valid| if valid { acc + 1 } else { acc });
if special_args != 2 {
return Err(err(span, msg))
}
let msg = r#"Should return one of the following:
- Result<(), TrapReason>,
- Result<ReturnErrorCode, TrapReason>,
- Result<u32, TrapReason>,
- Result<u64, TrapReason>"#;
let ret_ty = match item.clone().sig.output {
syn::ReturnType::Type(_, ty) => Ok(ty.clone()),
_ => Err(err(span, &msg)),
}?;
match *ret_ty {
syn::Type::Path(tp) => {
let result = &tp.path.segments.last().ok_or(err(span, &msg))?;
let (id, span) = (result.ident.to_string(), result.ident.span());
id.eq(&"Result".to_string()).then_some(()).ok_or(err(span, &msg))?;
match &result.arguments {
syn::PathArguments::AngleBracketed(group) => {
if group.args.len() != 2 {
return Err(err(span, &msg))
};
let arg2 = group.args.last().ok_or(err(span, &msg))?;
let err_ty = match arg2 {
syn::GenericArgument::Type(ty) => Ok(ty.clone()),
_ => Err(err(arg2.span(), &msg)),
}?;
match err_ty {
syn::Type::Path(tp) => Ok(tp
.path
.segments
.first()
.ok_or(err(arg2.span(), &msg))?
.ident
.to_string()),
_ => Err(err(tp.span(), &msg)),
}?
.eq("TrapReason")
.then_some(())
.ok_or(err(span, &msg))?;
let arg1 = group.args.first().ok_or(err(span, &msg))?;
let ok_ty = match arg1 {
syn::GenericArgument::Type(ty) => Ok(ty.clone()),
_ => Err(err(arg1.span(), &msg)),
}?;
let ok_ty_str = match ok_ty {
syn::Type::Path(tp) => Ok(tp
.path
.segments
.first()
.ok_or(err(arg1.span(), &msg))?
.ident
.to_string()),
syn::Type::Tuple(tt) => {
if !tt.elems.is_empty() {
return Err(err(arg1.span(), &msg))
};
Ok("()".to_string())
},
_ => Err(err(ok_ty.span(), &msg)),
}?;
let returns = match ok_ty_str.as_str() {
"()" => Ok(HostFnReturn::Unit),
"u32" => Ok(HostFnReturn::U32),
"u64" => Ok(HostFnReturn::U64),
"ReturnErrorCode" => Ok(HostFnReturn::ReturnCode),
_ => Err(err(arg1.span(), &msg)),
}?;
Ok(Self { item, is_stable, name, returns, cfg })
},
_ => Err(err(span, &msg)),
}
},
_ => Err(err(span, &msg)),
}
}
}
fn is_valid_special_arg(idx: usize, arg: &FnArg) -> bool {
match (idx, arg) {
(0, FnArg::Receiver(rec)) => rec.reference.is_some() && rec.mutability.is_some(),
(1, FnArg::Typed(pat)) => {
let ident =
if let syn::Pat::Ident(ref ident) = *pat.pat { &ident.ident } else { return false };
if !(ident == "memory" || ident == "_memory") {
return false
}
matches!(*pat.ty, syn::Type::Reference(_))
},
_ => false,
}
}
fn arg_decoder<'a, P, I>(param_names: P, param_types: I) -> TokenStream2
where
P: Iterator<Item = &'a std::boxed::Box<syn::Pat>> + Clone,
I: Iterator<Item = &'a std::boxed::Box<syn::Type>> + Clone,
{
const ALLOWED_REGISTERS: usize = 6;
if !param_types.clone().all(|ty| {
let syn::Type::Path(path) = &**ty else {
panic!("Type needs to be path");
};
let Some(ident) = path.path.get_ident() else {
panic!("Type needs to be ident");
};
matches!(ident.to_string().as_ref(), "u8" | "u16" | "u32" | "u64")
}) {
panic!("Only primitive unsigned integers are allowed as arguments to syscalls");
}
if param_names.clone().count() > ALLOWED_REGISTERS {
let fields = param_names.clone().zip(param_types.clone()).map(|(name, ty)| {
quote! {
#name: #ty,
}
});
return quote! {
#[derive(Default)]
#[repr(C)]
struct Args {
#(#fields)*
}
let Args { #(#param_names,)* } = {
let len = ::core::mem::size_of::<Args>();
let mut args = Args::default();
let ptr = &mut args as *mut Args as *mut u8;
let reference = unsafe {
::core::slice::from_raw_parts_mut(ptr, len)
};
memory.read_into_buf(__a0__ as _, reference)?;
args
};
}
}
let bindings = param_names.zip(param_types).enumerate().map(|(idx, (name, ty))| {
let reg = quote::format_ident!("__a{}__", idx);
quote! {
let #name = #reg as #ty;
}
});
quote! {
#( #bindings )*
}
}
fn expand_env(def: &EnvDef) -> TokenStream2 {
let impls = expand_functions(def);
let bench_impls = expand_bench_functions(def);
let docs = expand_func_doc(def);
let stable_syscalls = expand_func_list(def, false);
let all_syscalls = expand_func_list(def, true);
quote! {
pub fn list_syscalls(include_unstable: bool) -> &'static [&'static [u8]] {
if include_unstable {
#all_syscalls
} else {
#stable_syscalls
}
}
impl<'a, E: Ext, M: PolkaVmInstance<E::T>> Runtime<'a, E, M> {
fn handle_ecall(
&mut self,
memory: &mut M,
__syscall_symbol__: &[u8],
) -> Result<Option<u64>, TrapReason>
{
#impls
}
}
#[cfg(feature = "runtime-benchmarks")]
impl<'a, E: Ext, M: ?Sized + Memory<E::T>> Runtime<'a, E, M> {
#bench_impls
}
#[cfg(doc)]
pub trait SyscallDoc {
#docs
}
}
}
fn expand_functions(def: &EnvDef) -> TokenStream2 {
let impls = def.host_funcs.iter().map(|f| {
let params = f.item.sig.inputs.iter().skip(2);
let param_names = params.clone().filter_map(|arg| {
let FnArg::Typed(arg) = arg else {
return None;
};
Some(&arg.pat)
});
let param_types = params.clone().filter_map(|arg| {
let FnArg::Typed(arg) = arg else {
return None;
};
Some(&arg.ty)
});
let arg_decoder = arg_decoder(param_names, param_types);
let cfg = &f.cfg;
let name = &f.name;
let syscall_symbol = Literal::byte_string(name.as_bytes());
let body = &f.item.block;
let map_output = f.returns.map_output();
let output = &f.item.sig.output;
let wrapped_body_with_trace = {
let trace_fmt_args = params.clone().filter_map(|arg| match arg {
syn::FnArg::Receiver(_) => None,
syn::FnArg::Typed(p) => match *p.pat.clone() {
syn::Pat::Ident(ref pat_ident) => Some(pat_ident.ident.clone()),
_ => None,
},
});
let params_fmt_str = trace_fmt_args
.clone()
.map(|s| format!("{s}: {{:?}}"))
.collect::<Vec<_>>()
.join(", ");
let trace_fmt_str = format!("{}({}) = {{:?}}\n", name, params_fmt_str);
quote! {
let result = (|| #body)();
if ::log::log_enabled!(target: "runtime::revive::strace", ::log::Level::Trace) {
use core::fmt::Write;
let mut msg = alloc::string::String::default();
let _ = core::write!(&mut msg, #trace_fmt_str, #( #trace_fmt_args, )* result);
self.ext().append_debug_buffer(&msg);
}
result
}
};
quote! {
#cfg
#syscall_symbol => {
(|| #output {
#arg_decoder
#wrapped_body_with_trace
})().map(#map_output)
},
}
});
quote! {
let __gas_left_before__ = self
.ext
.gas_meter_mut()
.sync_from_executor(memory.gas())
.map_err(TrapReason::from)?;
self.charge_gas(crate::wasm::RuntimeCosts::HostFn).map_err(TrapReason::from)?;
let (__a0__, __a1__, __a2__, __a3__, __a4__, __a5__) = memory.read_input_regs();
let result = (|| match __syscall_symbol__ {
#( #impls )*
_ => Err(TrapReason::SupervisorError(Error::<E::T>::InvalidSyscall.into()))
})();
let gas = self.ext.gas_meter_mut().sync_to_executor(__gas_left_before__).map_err(TrapReason::from)?;
memory.set_gas(gas.into());
result
}
}
fn expand_bench_functions(def: &EnvDef) -> TokenStream2 {
let impls = def.host_funcs.iter().map(|f| {
let params = f.item.sig.inputs.iter().skip(2);
let cfg = &f.cfg;
let name = &f.name;
let body = &f.item.block;
let output = &f.item.sig.output;
let name = Ident::new(&format!("bench_{name}"), Span::call_site());
quote! {
#cfg
pub fn #name(&mut self, memory: &mut M, #(#params),*) #output {
#body
}
}
});
quote! {
#( #impls )*
}
}
fn expand_func_doc(def: &EnvDef) -> TokenStream2 {
let docs = def.host_funcs.iter().map(|func| {
let func_decl = {
let mut sig = func.item.sig.clone();
sig.inputs = sig
.inputs
.iter()
.skip(2)
.map(|p| p.clone())
.collect::<Punctuated<FnArg, Comma>>();
sig.output = func.returns.success_type();
sig.to_token_stream()
};
let func_doc = {
let func_docs = {
let docs = func.item.attrs.iter().filter(|a| a.path().is_ident("doc")).map(|d| {
let docs = d.to_token_stream();
quote! { #docs }
});
quote! { #( #docs )* }
};
let availability = if func.is_stable {
let info = "\n# Stable API\nThis API is stable and will never change.";
quote! { #[doc = #info] }
} else {
let info =
"\n# Unstable API\nThis API is not standardized and only available for testing.";
quote! { #[doc = #info] }
};
quote! {
#func_docs
#availability
}
};
quote! {
#func_doc
#func_decl;
}
});
quote! {
#( #docs )*
}
}
fn expand_func_list(def: &EnvDef, include_unstable: bool) -> TokenStream2 {
let docs = def.host_funcs.iter().filter(|f| include_unstable || f.is_stable).map(|f| {
let name = Literal::byte_string(f.name.as_bytes());
quote! {
#name.as_slice()
}
});
let len = docs.clone().count();
quote! {
{
static FUNCS: [&[u8]; #len] = [#(#docs),*];
FUNCS.as_slice()
}
}
}