rhai/codegen/src/function.rs

868 lines
31 KiB
Rust
Raw Normal View History

2021-10-20 07:36:40 +02:00
use proc_macro2::{Span, TokenStream};
use quote::{quote, quote_spanned, ToTokens};
use syn::{
parse::{Parse, ParseStream},
spanned::Spanned,
};
#[cfg(no_std)]
use alloc::format;
#[cfg(not(no_std))]
use std::format;
use std::borrow::Cow;
use crate::attrs::{ExportInfo, ExportScope, ExportedParams};
2020-08-24 00:53:30 +02:00
#[derive(Clone, Debug, Eq, PartialEq, Copy, Hash)]
pub enum FnNamespaceAccess {
2020-12-24 14:28:40 +01:00
Unset,
Global,
Internal,
}
2020-12-24 14:28:40 +01:00
impl Default for FnNamespaceAccess {
fn default() -> Self {
Self::Unset
}
}
#[derive(Clone, Debug, Eq, PartialEq, Copy, Hash)]
pub enum Index {
Get,
Set,
}
2020-12-24 14:28:40 +01:00
#[derive(Clone, Debug, Eq, PartialEq, Hash)]
pub enum Property {
Get(syn::Ident),
Set(syn::Ident),
}
2020-12-24 14:28:40 +01:00
#[derive(Clone, Debug, Eq, PartialEq, Hash)]
pub enum FnSpecialAccess {
None,
Index(Index),
Property(Property),
}
impl Default for FnSpecialAccess {
fn default() -> FnSpecialAccess {
FnSpecialAccess::None
}
}
impl FnSpecialAccess {
2021-10-20 07:36:40 +02:00
pub fn get_fn_name(&self) -> Option<(String, String, Span)> {
match self {
FnSpecialAccess::None => None,
FnSpecialAccess::Property(Property::Get(ref g)) => {
Some((format!("{}{}", FN_GET, g), g.to_string(), g.span()))
}
FnSpecialAccess::Property(Property::Set(ref s)) => {
Some((format!("{}{}", FN_SET, s), s.to_string(), s.span()))
}
FnSpecialAccess::Index(Index::Get) => Some((
FN_IDX_GET.to_string(),
"index_get".to_string(),
2021-10-20 07:36:40 +02:00
Span::call_site(),
)),
FnSpecialAccess::Index(Index::Set) => Some((
FN_IDX_SET.to_string(),
"index_set".to_string(),
2021-10-20 07:36:40 +02:00
Span::call_site(),
)),
}
}
}
2021-02-21 07:11:19 +01:00
pub fn flatten_type_groups(ty: &syn::Type) -> &syn::Type {
match ty {
syn::Type::Group(syn::TypeGroup { ref elem, .. })
| syn::Type::Paren(syn::TypeParen { ref elem, .. }) => flatten_type_groups(elem.as_ref()),
_ => ty,
}
}
2021-02-21 07:11:19 +01:00
pub fn print_type(ty: &syn::Type) -> String {
2020-11-22 15:15:17 +01:00
ty.to_token_stream()
.to_string()
.replace(" , ", ", ")
.replace("& ", "&")
.replace(" :: ", "::")
.replace(" ( ", "(")
.replace(" ) ", ")")
.replace(" < ", "<")
.replace(" > ", ">")
2020-11-22 10:21:34 +01:00
}
2020-08-08 04:19:17 +02:00
#[derive(Debug, Default)]
2021-02-21 07:11:19 +01:00
pub struct ExportedFnParams {
2020-12-23 16:29:19 +01:00
pub name: Vec<String>,
2021-10-20 07:36:40 +02:00
pub return_raw: Option<Span>,
pub pure: Option<Span>,
pub skip: bool,
pub special: FnSpecialAccess,
2020-12-24 14:28:40 +01:00
pub namespace: FnNamespaceAccess,
2021-10-20 07:36:40 +02:00
pub span: Option<Span>,
}
pub const FN_GET: &str = "get$";
pub const FN_SET: &str = "set$";
2020-08-17 17:35:04 +02:00
pub const FN_IDX_GET: &str = "index$get$";
pub const FN_IDX_SET: &str = "index$set$";
2020-08-08 04:19:17 +02:00
impl Parse for ExportedFnParams {
fn parse(args: ParseStream) -> syn::Result<Self> {
if args.is_empty() {
return Ok(ExportedFnParams::default());
}
2020-08-24 00:53:30 +02:00
let info = crate::attrs::parse_attr_items(args)?;
Self::from_info(info)
}
}
2020-08-08 04:19:17 +02:00
2020-08-24 00:53:30 +02:00
impl ExportedParams for ExportedFnParams {
fn parse_stream(args: ParseStream) -> syn::Result<Self> {
Self::parse(args)
}
fn no_attrs() -> Self {
Default::default()
}
2020-09-04 05:57:40 +02:00
fn from_info(info: crate::attrs::ExportInfo) -> syn::Result<Self> {
let ExportInfo {
item_span: span,
items: attrs,
} = info;
let mut name = Vec::new();
2021-02-26 11:28:21 +01:00
let mut return_raw = None;
let mut pure = None;
let mut skip = false;
2020-12-24 14:28:40 +01:00
let mut namespace = FnNamespaceAccess::Unset;
let mut special = FnSpecialAccess::None;
2020-08-24 00:53:30 +02:00
for attr in attrs {
let crate::attrs::AttrItem {
key,
value,
span: item_span,
} = attr;
2020-08-24 00:53:30 +02:00
match (key.to_string().as_ref(), value) {
2020-09-09 23:24:37 +02:00
("get", None) | ("set", None) | ("name", None) => {
return Err(syn::Error::new(key.span(), "requires value"))
}
2021-07-24 08:11:16 +02:00
("name", Some(s)) if s.value() == FN_IDX_GET => {
return Err(syn::Error::new(
item_span,
"use attribute 'index_get' instead",
))
}
2021-07-24 08:11:16 +02:00
("name", Some(s)) if s.value() == FN_IDX_SET => {
return Err(syn::Error::new(
item_span,
"use attribute 'index_set' instead",
))
}
("name", Some(s)) if s.value().starts_with(FN_GET) => {
return Err(syn::Error::new(
item_span,
format!(
"use attribute 'getter = \"{}\"' instead",
&s.value()[FN_GET.len()..]
),
))
}
("name", Some(s)) if s.value().starts_with(FN_SET) => {
return Err(syn::Error::new(
item_span,
format!(
"use attribute 'setter = \"{}\"' instead",
&s.value()[FN_SET.len()..]
),
))
}
("name", Some(s)) => name.push(s.value()),
2021-02-21 07:11:19 +01:00
("index_get", Some(s))
| ("index_set", Some(s))
| ("return_raw", Some(s))
| ("pure", Some(s))
| ("skip", Some(s))
| ("global", Some(s))
| ("internal", Some(s)) => {
return Err(syn::Error::new(s.span(), "extraneous value"))
}
2021-02-26 11:28:21 +01:00
("pure", None) => pure = Some(item_span),
("return_raw", None) => return_raw = Some(item_span),
2021-02-21 07:11:19 +01:00
("skip", None) => skip = true,
("global", None) => match namespace {
FnNamespaceAccess::Unset => namespace = FnNamespaceAccess::Global,
FnNamespaceAccess::Global => (),
2021-02-26 13:00:25 +01:00
FnNamespaceAccess::Internal => {
return Err(syn::Error::new(
key.span(),
"namespace is already set to 'internal'",
))
}
2021-02-21 07:11:19 +01:00
},
("internal", None) => match namespace {
FnNamespaceAccess::Unset => namespace = FnNamespaceAccess::Internal,
FnNamespaceAccess::Internal => (),
2021-02-26 13:00:25 +01:00
FnNamespaceAccess::Global => {
return Err(syn::Error::new(
key.span(),
"namespace is already set to 'global'",
))
}
2021-02-21 07:11:19 +01:00
},
("get", Some(s)) => {
special = match special {
2021-02-21 07:11:19 +01:00
FnSpecialAccess::None => FnSpecialAccess::Property(Property::Get(
syn::Ident::new(&s.value(), s.span()),
)),
2021-02-21 07:11:19 +01:00
_ => return Err(syn::Error::new(item_span.span(), "conflicting getter")),
}
}
2021-02-21 07:11:19 +01:00
("set", Some(s)) => {
special = match special {
2021-02-21 07:11:19 +01:00
FnSpecialAccess::None => FnSpecialAccess::Property(Property::Set(
syn::Ident::new(&s.value(), s.span()),
)),
2021-02-21 07:11:19 +01:00
_ => return Err(syn::Error::new(item_span.span(), "conflicting setter")),
}
}
("index_get", None) => {
special = match special {
FnSpecialAccess::None => FnSpecialAccess::Index(Index::Get),
_ => {
return Err(syn::Error::new(item_span.span(), "conflicting index_get"))
}
}
}
("index_set", None) => {
special = match special {
FnSpecialAccess::None => FnSpecialAccess::Index(Index::Set),
_ => {
return Err(syn::Error::new(item_span.span(), "conflicting index_set"))
}
}
}
2021-02-21 07:11:19 +01:00
2020-08-09 21:19:39 +02:00
(attr, _) => {
return Err(syn::Error::new(
2020-08-24 00:53:30 +02:00
key.span(),
2020-08-09 21:19:39 +02:00
format!("unknown attribute '{}'", attr),
))
}
}
}
2020-08-08 04:19:17 +02:00
2020-08-16 12:24:42 +02:00
Ok(ExportedFnParams {
2020-12-23 16:29:19 +01:00
name,
2020-08-16 12:24:42 +02:00
return_raw,
2021-02-19 16:13:41 +01:00
pure,
2020-08-16 12:24:42 +02:00
skip,
special,
namespace,
span: Some(span),
2020-08-16 12:24:42 +02:00
})
2020-08-08 04:19:17 +02:00
}
}
2020-08-01 18:52:26 +02:00
#[derive(Debug)]
2021-02-21 07:11:19 +01:00
pub struct ExportedFn {
2021-10-20 07:36:40 +02:00
entire_span: Span,
2020-08-01 18:52:26 +02:00
signature: syn::Signature,
visibility: syn::Visibility,
pass_context: bool,
2020-08-01 18:52:26 +02:00
mut_receiver: bool,
params: ExportedFnParams,
2021-10-20 09:30:11 +02:00
cfg_attrs: Vec<syn::Attribute>,
2020-08-01 18:52:26 +02:00
}
impl Parse for ExportedFn {
fn parse(input: ParseStream) -> syn::Result<Self> {
let fn_all: syn::ItemFn = input.parse()?;
let entire_span = fn_all.span();
let str_type_path = syn::parse2::<syn::Path>(quote! { str }).unwrap();
let context_type_path1 = syn::parse2::<syn::Path>(quote! { NativeCallContext }).unwrap();
let context_type_path2 =
syn::parse2::<syn::Path>(quote! { rhai::NativeCallContext }).unwrap();
let mut pass_context = false;
2021-10-20 09:30:11 +02:00
let cfg_attrs = crate::attrs::collect_cfg_attr(&fn_all.attrs);
let visibility = fn_all.vis;
// Determine if the function requires a call context
2021-03-24 03:02:50 +01:00
match fn_all.sig.inputs.first() {
Some(syn::FnArg::Typed(syn::PatType { ref ty, .. })) => {
match flatten_type_groups(ty.as_ref()) {
syn::Type::Path(p)
if p.path == context_type_path1 || p.path == context_type_path2 =>
{
pass_context = true;
}
2021-03-24 03:02:50 +01:00
_ => {}
}
}
2021-03-24 03:02:50 +01:00
_ => {}
}
let skip_slots = if pass_context { 1 } else { 0 };
// Determine whether function generates a special calling convention for a mutable receiver.
2021-07-24 08:11:16 +02:00
let mut_receiver = match fn_all.sig.inputs.iter().nth(skip_slots) {
2021-03-24 03:02:50 +01:00
Some(syn::FnArg::Receiver(syn::Receiver {
reference: Some(_), ..
})) => true,
Some(syn::FnArg::Typed(syn::PatType { ref ty, .. })) => {
match flatten_type_groups(ty.as_ref()) {
syn::Type::Reference(syn::TypeReference {
mutability: Some(_),
..
2020-08-02 09:39:08 +02:00
}) => true,
2021-03-24 03:02:50 +01:00
syn::Type::Reference(syn::TypeReference {
mutability: None,
ref elem,
..
}) => match flatten_type_groups(elem.as_ref()) {
syn::Type::Path(ref p) if p.path == str_type_path => false,
_ => {
return Err(syn::Error::new(
ty.span(),
"references from Rhai in this position must be mutable",
))
2020-09-22 16:19:21 +02:00
}
2021-03-24 03:02:50 +01:00
},
2020-08-01 18:52:26 +02:00
_ => false,
}
}
2021-03-24 03:02:50 +01:00
_ => false,
2020-08-01 18:52:26 +02:00
};
// All arguments after the first must be moved except for &str.
for arg in fn_all.sig.inputs.iter().skip(skip_slots + 1) {
2020-08-01 18:52:26 +02:00
let ty = match arg {
syn::FnArg::Typed(syn::PatType { ref ty, .. }) => ty,
_ => panic!("internal error: receiver argument outside of first position!?"),
};
2020-09-22 16:19:21 +02:00
let is_ok = match flatten_type_groups(ty.as_ref()) {
syn::Type::Reference(syn::TypeReference {
2020-08-02 09:39:08 +02:00
mutability: Some(_),
..
}) => false,
syn::Type::Reference(syn::TypeReference {
2020-08-02 09:39:08 +02:00
mutability: None,
ref elem,
..
2020-09-22 16:19:21 +02:00
}) => {
2020-10-15 08:06:54 +02:00
matches!(flatten_type_groups(elem.as_ref()), syn::Type::Path(ref p) if p.path == str_type_path)
2020-09-22 16:19:21 +02:00
}
syn::Type::Verbatim(_) => false,
2020-08-01 18:52:26 +02:00
_ => true,
};
if !is_ok {
2020-08-02 09:39:08 +02:00
return Err(syn::Error::new(
ty.span(),
2021-10-20 07:36:40 +02:00
"function parameters other than the first one cannot be passed by reference",
2020-08-02 09:39:08 +02:00
));
2020-08-01 18:52:26 +02:00
}
}
// Check return type.
2021-03-24 03:02:50 +01:00
match fn_all.sig.output {
syn::ReturnType::Type(_, ref ret_type) => {
match flatten_type_groups(ret_type.as_ref()) {
syn::Type::Ptr(_) => {
return Err(syn::Error::new(
fn_all.sig.output.span(),
"Rhai functions cannot return pointers",
))
}
syn::Type::Reference(_) => {
return Err(syn::Error::new(
fn_all.sig.output.span(),
"Rhai functions cannot return references",
))
}
_ => {}
2020-08-02 09:39:08 +02:00
}
2020-08-01 18:52:26 +02:00
}
2021-03-24 03:02:50 +01:00
_ => {}
2020-08-01 18:52:26 +02:00
}
Ok(ExportedFn {
entire_span,
signature: fn_all.sig,
visibility,
pass_context,
2020-08-01 18:52:26 +02:00
mut_receiver,
2020-10-20 03:21:41 +02:00
params: Default::default(),
2021-10-20 09:30:11 +02:00
cfg_attrs,
2020-08-01 18:52:26 +02:00
})
}
}
impl ExportedFn {
2021-02-21 08:44:01 +01:00
#![allow(unused)]
2021-02-21 07:11:19 +01:00
pub fn params(&self) -> &ExportedFnParams {
&self.params
}
2021-10-20 09:30:11 +02:00
pub fn cfg_attrs(&self) -> &[syn::Attribute] {
&self.cfg_attrs
}
2021-02-21 07:11:19 +01:00
pub fn update_scope(&mut self, parent_scope: &ExportScope) {
let keep = match (self.params.skip, parent_scope) {
(true, _) => false,
(_, ExportScope::PubOnly) => self.is_public(),
(_, ExportScope::Prefix(s)) => self.name().to_string().starts_with(s),
(_, ExportScope::All) => true,
};
self.params.skip = !keep;
}
2021-02-21 07:11:19 +01:00
pub fn skipped(&self) -> bool {
self.params.skip
}
2021-02-21 07:11:19 +01:00
pub fn pass_context(&self) -> bool {
self.pass_context
}
2021-02-21 07:11:19 +01:00
pub fn signature(&self) -> &syn::Signature {
&self.signature
}
2021-02-21 07:11:19 +01:00
pub fn mutable_receiver(&self) -> bool {
2020-08-01 18:52:26 +02:00
self.mut_receiver
}
2021-02-21 07:11:19 +01:00
pub fn is_public(&self) -> bool {
!matches!(self.visibility, syn::Visibility::Inherited)
2020-08-01 18:52:26 +02:00
}
2021-10-20 07:36:40 +02:00
pub fn span(&self) -> &Span {
2020-08-01 18:52:26 +02:00
&self.entire_span
}
2021-02-21 07:11:19 +01:00
pub fn name(&self) -> &syn::Ident {
2020-08-01 18:52:26 +02:00
&self.signature.ident
}
2021-02-21 07:11:19 +01:00
pub fn exported_names(&self) -> Vec<syn::LitStr> {
2020-12-23 16:29:19 +01:00
let mut literals: Vec<_> = self
.params
.name
2020-12-23 16:29:19 +01:00
.iter()
2021-10-20 07:36:40 +02:00
.map(|s| syn::LitStr::new(s, Span::call_site()))
2020-12-23 16:29:19 +01:00
.collect();
if let Some((s, _, span)) = self.params.special.get_fn_name() {
literals.push(syn::LitStr::new(&s, span));
}
if literals.is_empty() {
literals.push(syn::LitStr::new(
&self.signature.ident.to_string(),
self.signature.ident.span(),
));
}
literals
}
2021-07-24 08:11:16 +02:00
pub fn exported_name(&self) -> Cow<str> {
2021-02-26 13:00:25 +01:00
self.params
.name
.last()
.map_or_else(|| self.signature.ident.to_string().into(), |s| s.into())
}
2021-02-21 07:11:19 +01:00
pub fn arg_list(&self) -> impl Iterator<Item = &syn::FnArg> {
let skip = if self.pass_context { 1 } else { 0 };
self.signature.inputs.iter().skip(skip)
2020-08-01 18:52:26 +02:00
}
2021-02-21 07:11:19 +01:00
pub fn arg_count(&self) -> usize {
let skip = if self.pass_context { 1 } else { 0 };
self.signature.inputs.len() - skip
2020-08-01 18:52:26 +02:00
}
2021-02-21 07:11:19 +01:00
pub fn return_type(&self) -> Option<&syn::Type> {
2021-03-24 03:02:50 +01:00
match self.signature.output {
syn::ReturnType::Type(_, ref ret_type) => Some(flatten_type_groups(ret_type)),
_ => None,
2020-08-01 18:52:26 +02:00
}
}
2021-10-20 09:30:11 +02:00
pub fn set_cfg_attrs(&mut self, cfg_attrs: Vec<syn::Attribute>) {
self.cfg_attrs = cfg_attrs
}
2020-08-24 00:53:30 +02:00
pub fn set_params(&mut self, mut params: ExportedFnParams) -> syn::Result<()> {
// Several issues are checked here to avoid issues with diagnostics caused by raising them later.
//
// 1a. Do not allow non-returning raw functions.
//
2021-02-26 11:28:21 +01:00
if params.return_raw.is_some() && self.return_type().is_none() {
2020-08-24 00:53:30 +02:00
return Err(syn::Error::new(
2021-02-26 11:28:21 +01:00
params.return_raw.unwrap(),
2021-03-22 04:18:09 +01:00
"functions marked with 'return_raw' must return Result<T, Box<EvalAltResult>>",
2020-08-24 00:53:30 +02:00
));
}
// 1b. Do not allow non-method pure functions.
//
2021-02-26 11:28:21 +01:00
if params.pure.is_some() && !self.mutable_receiver() {
return Err(syn::Error::new(
2021-02-26 11:28:21 +01:00
params.pure.unwrap(),
2021-02-26 13:00:25 +01:00
"'pure' is not necessary on functions without a &mut first parameter",
));
}
match params.special {
// 2a. Property getters must take only the subject as an argument.
FnSpecialAccess::Property(Property::Get(_)) if self.arg_count() != 1 => {
return Err(syn::Error::new(
2021-02-26 13:14:23 +01:00
self.signature.inputs.span(),
2020-10-20 03:21:41 +02:00
"property getter requires exactly 1 parameter",
))
}
// 2b. Property getters must return a value.
FnSpecialAccess::Property(Property::Get(_)) if self.return_type().is_none() => {
return Err(syn::Error::new(
self.signature.span(),
"property getter must return a value",
))
}
// 3a. Property setters must take the subject and a new value as arguments.
FnSpecialAccess::Property(Property::Set(_)) if self.arg_count() != 2 => {
return Err(syn::Error::new(
2021-02-26 13:00:25 +01:00
self.signature.inputs.span(),
2020-10-20 03:21:41 +02:00
"property setter requires exactly 2 parameters",
))
}
// 3b. Non-raw property setters must return nothing.
FnSpecialAccess::Property(Property::Set(_))
if params.return_raw.is_none() && self.return_type().is_some() =>
{
return Err(syn::Error::new(
2021-02-26 13:00:25 +01:00
self.signature.output.span(),
"property setter cannot return any value",
))
}
// 4a. Index getters must take the subject and the accessed "index" as arguments.
FnSpecialAccess::Index(Index::Get) if self.arg_count() != 2 => {
return Err(syn::Error::new(
2021-02-26 13:00:25 +01:00
self.signature.inputs.span(),
2020-10-20 03:21:41 +02:00
"index getter requires exactly 2 parameters",
))
}
// 4b. Index getters must return a value.
FnSpecialAccess::Index(Index::Get) if self.return_type().is_none() => {
return Err(syn::Error::new(
self.signature.span(),
"index getter must return a value",
))
}
// 5a. Index setters must take the subject, "index", and new value as arguments.
FnSpecialAccess::Index(Index::Set) if self.arg_count() != 3 => {
return Err(syn::Error::new(
2021-02-26 13:00:25 +01:00
self.signature.inputs.span(),
2020-10-20 03:21:41 +02:00
"index setter requires exactly 3 parameters",
))
}
// 5b. Non-raw index setters must return nothing.
FnSpecialAccess::Index(Index::Set)
if params.return_raw.is_none() && self.return_type().is_some() =>
{
return Err(syn::Error::new(
2021-02-26 13:00:25 +01:00
self.signature.output.span(),
"index setter cannot return any value",
))
}
_ => {}
}
2020-08-08 04:19:17 +02:00
self.params = params;
Ok(())
2020-08-08 04:19:17 +02:00
}
2021-10-20 07:36:40 +02:00
pub fn generate(self) -> TokenStream {
let name: syn::Ident =
2020-08-16 12:24:42 +02:00
syn::Ident::new(&format!("rhai_fn_{}", self.name()), self.name().span());
2020-08-01 18:52:26 +02:00
let impl_block = self.generate_impl("Token");
let dyn_result_fn_block = self.generate_dynamic_fn();
let vis = self.visibility;
2020-08-01 18:52:26 +02:00
quote! {
#[automatically_derived]
#vis mod #name {
2020-08-01 18:52:26 +02:00
use super::*;
pub struct Token();
2020-08-01 18:52:26 +02:00
#impl_block
#dyn_result_fn_block
}
}
}
2021-10-20 07:36:40 +02:00
pub fn generate_dynamic_fn(&self) -> TokenStream {
2020-08-16 12:24:42 +02:00
let name = self.name().clone();
let mut dynamic_signature = self.signature.clone();
2021-10-20 07:36:40 +02:00
dynamic_signature.ident = syn::Ident::new("dynamic_result_fn", Span::call_site());
dynamic_signature.output = syn::parse2::<syn::ReturnType>(quote! {
-> RhaiResult
})
.unwrap();
2021-10-20 07:36:40 +02:00
let arguments: Vec<_> = dynamic_signature
.inputs
.iter()
2021-03-24 03:02:50 +01:00
.filter_map(|fn_arg| match fn_arg {
syn::FnArg::Typed(syn::PatType { ref pat, .. }) => match pat.as_ref() {
syn::Pat::Ident(ref ident) => Some(ident.ident.clone()),
_ => None,
},
_ => None,
})
.collect();
2020-09-04 05:57:40 +02:00
let return_span = self
.return_type()
.map(|r| r.span())
2021-10-20 07:36:40 +02:00
.unwrap_or_else(Span::call_site);
2021-02-26 11:28:21 +01:00
if self.params.return_raw.is_some() {
2021-02-19 16:13:41 +01:00
quote_spanned! { return_span =>
pub #dynamic_signature {
2021-03-22 04:18:09 +01:00
#name(#(#arguments),*).map(Dynamic::from)
}
}
} else {
2021-02-19 16:13:41 +01:00
quote_spanned! { return_span =>
2021-03-22 16:11:23 +01:00
#[allow(unused)]
#[inline(always)]
pub #dynamic_signature {
2020-10-20 03:21:41 +02:00
Ok(Dynamic::from(#name(#(#arguments),*)))
}
2020-08-03 02:27:19 +02:00
}
}
}
2021-10-20 07:36:40 +02:00
pub fn generate_impl(&self, on_type_name: &str) -> TokenStream {
2020-08-16 12:24:42 +02:00
let sig_name = self.name().clone();
2020-08-01 18:52:26 +02:00
let arg_count = self.arg_count();
let is_method_call = self.mutable_receiver();
2021-10-20 07:36:40 +02:00
let mut unpack_statements = Vec::new();
let mut unpack_exprs = Vec::new();
#[cfg(feature = "metadata")]
2021-10-20 07:36:40 +02:00
let mut input_type_names = Vec::new();
let mut input_type_exprs = Vec::new();
2020-11-22 15:15:17 +01:00
let return_type = self
.return_type()
.map(print_type)
.unwrap_or_else(|| "()".to_string());
2020-08-01 18:52:26 +02:00
let skip_first_arg;
if self.pass_context {
unpack_exprs.push(syn::parse2::<syn::Expr>(quote! { context }).unwrap());
}
2020-08-01 18:52:26 +02:00
// Handle the first argument separately if the function has a "method like" receiver
if is_method_call {
skip_first_arg = true;
let first_arg = self.arg_list().next().unwrap();
2021-10-20 07:36:40 +02:00
let var = syn::Ident::new("arg0", Span::call_site());
2020-08-01 18:52:26 +02:00
match first_arg {
2020-11-22 10:21:34 +01:00
syn::FnArg::Typed(syn::PatType { pat, ty, .. }) => {
#[cfg(feature = "metadata")]
2020-11-22 10:21:34 +01:00
let arg_name = format!("{}: {}", pat.to_token_stream(), print_type(ty));
let arg_type = match flatten_type_groups(ty.as_ref()) {
2020-10-15 08:06:54 +02:00
syn::Type::Reference(syn::TypeReference { ref elem, .. }) => elem.as_ref(),
2020-09-22 16:19:21 +02:00
p => p,
2020-08-01 18:52:26 +02:00
};
2021-02-19 16:13:41 +01:00
let downcast_span = quote_spanned!(arg_type.span() =>
&mut args[0usize].write_lock::<#arg_type>().unwrap()
);
2021-02-18 10:42:49 +01:00
unpack_statements.push(
2020-08-02 09:39:08 +02:00
syn::parse2::<syn::Stmt>(quote! {
let #var = #downcast_span;
2020-08-02 09:39:08 +02:00
})
.unwrap(),
);
2021-07-24 08:11:16 +02:00
if self.params().pure.is_none() {
2021-02-19 16:13:41 +01:00
let arg_lit_str =
syn::LitStr::new(&pat.to_token_stream().to_string(), pat.span());
unpack_statements.push(
syn::parse2::<syn::Stmt>(quote! {
if args[0usize].is_read_only() {
return Err(EvalAltResult::ErrorAssignmentToConstant(#arg_lit_str.to_string(), Position::NONE).into());
2021-02-19 16:13:41 +01:00
}
})
.unwrap(),
);
}
#[cfg(feature = "metadata")]
2020-11-22 10:21:34 +01:00
input_type_names.push(arg_name);
2020-08-02 09:39:08 +02:00
input_type_exprs.push(
2021-02-19 16:13:41 +01:00
syn::parse2::<syn::Expr>(quote_spanned!(arg_type.span() =>
TypeId::of::<#arg_type>()
2020-08-02 09:39:08 +02:00
))
.unwrap(),
);
}
2020-08-01 18:52:26 +02:00
syn::FnArg::Receiver(_) => todo!("true self parameters not implemented yet"),
}
unpack_exprs.push(syn::parse2::<syn::Expr>(quote! { #var }).unwrap());
} else {
skip_first_arg = false;
}
// Handle the rest of the arguments, which all are passed by value.
//
// The only exception is strings, which need to be downcast to ImmutableString to enable a
2020-09-19 12:18:40 +02:00
// zero-copy conversion to &str by reference, or a cloned String.
2020-08-01 18:52:26 +02:00
let str_type_path = syn::parse2::<syn::Path>(quote! { str }).unwrap();
2020-09-19 12:18:40 +02:00
let string_type_path = syn::parse2::<syn::Path>(quote! { String }).unwrap();
2020-08-01 18:52:26 +02:00
for (i, arg) in self.arg_list().enumerate().skip(skip_first_arg as usize) {
2021-10-20 07:36:40 +02:00
let var = syn::Ident::new(&format!("arg{}", i), Span::call_site());
2020-09-19 12:18:40 +02:00
let is_string;
let is_ref;
2020-08-01 18:52:26 +02:00
match arg {
2020-11-22 10:21:34 +01:00
syn::FnArg::Typed(syn::PatType { pat, ty, .. }) => {
#[cfg(feature = "metadata")]
2020-11-22 10:21:34 +01:00
let arg_name = format!("{}: {}", pat.to_token_stream(), print_type(ty));
let arg_type = ty.as_ref();
let downcast_span = match flatten_type_groups(arg_type) {
2020-10-15 08:06:54 +02:00
syn::Type::Reference(syn::TypeReference {
2020-08-02 09:39:08 +02:00
mutability: None,
ref elem,
..
2020-09-22 16:19:21 +02:00
}) => match flatten_type_groups(elem.as_ref()) {
2020-10-15 08:06:54 +02:00
syn::Type::Path(ref p) if p.path == str_type_path => {
2020-09-19 12:18:40 +02:00
is_string = true;
is_ref = true;
2021-02-19 16:13:41 +01:00
quote_spanned!(arg_type.span() =>
mem::take(args[#i]).into_immutable_string().unwrap()
2021-02-19 16:13:41 +01:00
)
2020-08-01 18:52:26 +02:00
}
2020-08-02 09:39:08 +02:00
_ => panic!("internal error: why wasn't this found earlier!?"),
2020-08-01 18:52:26 +02:00
},
2020-10-15 08:06:54 +02:00
syn::Type::Path(ref p) if p.path == string_type_path => {
2020-09-19 12:18:40 +02:00
is_string = true;
is_ref = false;
2021-02-19 16:13:41 +01:00
quote_spanned!(arg_type.span() =>
mem::take(args[#i]).into_string().unwrap()
2021-02-19 16:13:41 +01:00
)
2020-09-19 12:18:40 +02:00
}
2020-08-01 18:52:26 +02:00
_ => {
2020-09-19 12:18:40 +02:00
is_string = false;
is_ref = false;
2021-02-19 16:13:41 +01:00
quote_spanned!(arg_type.span() =>
mem::take(args[#i]).cast::<#arg_type>()
)
2020-08-02 09:39:08 +02:00
}
2020-08-01 18:52:26 +02:00
};
2021-02-18 10:42:49 +01:00
unpack_statements.push(
2020-08-02 09:39:08 +02:00
syn::parse2::<syn::Stmt>(quote! {
let #var = #downcast_span;
})
.unwrap(),
);
#[cfg(feature = "metadata")]
2020-11-22 10:21:34 +01:00
input_type_names.push(arg_name);
2020-09-19 12:18:40 +02:00
if !is_string {
2020-08-02 09:39:08 +02:00
input_type_exprs.push(
2021-02-19 16:13:41 +01:00
syn::parse2::<syn::Expr>(quote_spanned!(arg_type.span() =>
TypeId::of::<#arg_type>()
2020-08-02 09:39:08 +02:00
))
.unwrap(),
);
2020-08-01 18:52:26 +02:00
} else {
2020-08-02 09:39:08 +02:00
input_type_exprs.push(
2021-02-19 16:13:41 +01:00
syn::parse2::<syn::Expr>(quote_spanned!(arg_type.span() =>
TypeId::of::<ImmutableString>()
2020-08-02 09:39:08 +02:00
))
.unwrap(),
);
2020-08-01 18:52:26 +02:00
}
2020-08-02 09:39:08 +02:00
}
2020-08-01 18:52:26 +02:00
syn::FnArg::Receiver(_) => panic!("internal error: how did this happen!?"),
}
2020-09-19 12:18:40 +02:00
if !is_ref {
2020-08-01 18:52:26 +02:00
unpack_exprs.push(syn::parse2::<syn::Expr>(quote! { #var }).unwrap());
} else {
unpack_exprs.push(syn::parse2::<syn::Expr>(quote! { &#var }).unwrap());
}
}
// In method calls, the first argument will need to be mutably borrowed. Because Rust marks
// that as needing to borrow the entire array, all of the previous argument unpacking via
// clone needs to happen first.
if is_method_call {
2021-02-18 10:42:49 +01:00
let arg0 = unpack_statements.remove(0);
unpack_statements.push(arg0);
2020-08-01 18:52:26 +02:00
}
2020-08-09 21:19:39 +02:00
// Handle "raw returns", aka cases where the result is a dynamic or an error.
//
// This allows skipping the Dynamic::from wrap.
2020-09-04 05:57:40 +02:00
let return_span = self
.return_type()
.map(|r| r.span())
2021-10-20 07:36:40 +02:00
.unwrap_or_else(Span::call_site);
2021-07-24 08:11:16 +02:00
let return_expr = if self.params.return_raw.is_none() {
2021-03-22 04:18:09 +01:00
quote_spanned! { return_span =>
Ok(Dynamic::from(#sig_name(#(#unpack_exprs),*)))
2020-08-09 21:19:39 +02:00
}
} else {
2021-02-19 16:13:41 +01:00
quote_spanned! { return_span =>
2021-03-22 04:18:09 +01:00
#sig_name(#(#unpack_exprs),*).map(Dynamic::from)
2020-08-09 21:19:39 +02:00
}
};
2021-10-20 07:36:40 +02:00
let type_name = syn::Ident::new(on_type_name, Span::call_site());
#[cfg(feature = "metadata")]
let param_names = quote! {
pub const PARAM_NAMES: &'static [&'static str] = &[#(#input_type_names,)* #return_type];
};
#[cfg(not(feature = "metadata"))]
let param_names = quote! {};
2021-10-20 09:30:11 +02:00
let cfg_attrs: Vec<_> = self
.cfg_attrs()
.iter()
.map(syn::Attribute::to_token_stream)
.collect();
2020-08-01 18:52:26 +02:00
quote! {
2021-10-20 09:30:11 +02:00
#(#cfg_attrs)*
impl #type_name {
#param_names
#[inline(always)] pub fn param_types() -> [TypeId; #arg_count] { [#(#input_type_exprs),*] }
}
2021-10-20 09:30:11 +02:00
#(#cfg_attrs)*
2020-08-03 02:27:19 +02:00
impl PluginFunction for #type_name {
2021-03-22 16:11:23 +01:00
#[inline(always)]
2021-03-19 03:30:30 +01:00
fn call(&self, context: NativeCallContext, args: &mut [&mut Dynamic]) -> RhaiResult {
2021-02-18 10:42:49 +01:00
#(#unpack_statements)*
2020-08-09 21:19:39 +02:00
#return_expr
2020-08-01 18:52:26 +02:00
}
2021-03-22 16:11:23 +01:00
#[inline(always)] fn is_method_call(&self) -> bool { #is_method_call }
2020-08-01 18:52:26 +02:00
}
}
}
}