Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve nif macro error messages for invalid attributes #525

Merged
merged 1 commit into from
Mar 27, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion rustler_codegen/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ version = "0.27.0" # rustler_codegen version
authors = ["Hansihe <hansihe@hansihe.com>"]
license = "MIT/Apache-2.0"
readme = "../README.md"
edition = "2018"
edition = "2021"

[lib]
name = "rustler_codegen"
Expand All @@ -17,3 +17,6 @@ syn = { version = "2.0", features = ["full", "extra-traits"] }
quote = "1.0"
heck = "0.4"
proc-macro2 = "1.0"

[dev-dependencies]
trybuild = "1.0"
18 changes: 3 additions & 15 deletions rustler_codegen/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
#![recursion_limit = "128"]

use proc_macro::TokenStream;
use syn::LitStr;

mod context;
mod encode_decode_templates;
Expand Down Expand Up @@ -92,28 +91,17 @@ pub fn init(input: TokenStream) -> TokenStream {
/// ```
#[proc_macro_attribute]
pub fn nif(args: TokenStream, input: TokenStream) -> TokenStream {
let mut schedule: Option<LitStr> = None;
let mut custom_name: Option<LitStr> = None;
let mut nif_attributes = nif::NifAttributes::default();

if !args.is_empty() {
let nif_macro_parser = syn::meta::parser(|meta| {
if meta.path.is_ident("schedule") {
schedule = Some(meta.value()?.parse()?);
Ok(())
} else if meta.path.is_ident("name") {
custom_name = Some(meta.value()?.parse()?);
Ok(())
} else {
Err(meta.error("Unsupported nif macro property. Expecting schedule or name."))
}
});
let nif_macro_parser = syn::meta::parser(|meta| nif_attributes.parse(meta));

syn::parse_macro_input!(args with nif_macro_parser);
}

let input = syn::parse_macro_input!(input as syn::ItemFn);

nif::transcoder_decorator(schedule, custom_name, input).into()
nif::transcoder_decorator(nif_attributes, input).into()
}

/// Derives implementations for the `Encoder` and `Decoder` traits
Expand Down
57 changes: 37 additions & 20 deletions rustler_codegen/src/nif.rs
Original file line number Diff line number Diff line change
@@ -1,24 +1,53 @@
use proc_macro2::{Span, TokenStream};
use quote::{quote, ToTokens};
use syn::meta::ParseNestedMeta;
use syn::punctuated::Punctuated;
use syn::token::Comma;
use syn::LitStr;

pub fn transcoder_decorator(
const VALID_SCHEDULE_OPTIONS: [&str; 3] = ["Normal", "DirtyCpu", "DirtyIo"];

#[derive(Default)]
pub struct NifAttributes {
schedule: Option<LitStr>,
custom_name: Option<LitStr>,
fun: syn::ItemFn,
) -> TokenStream {
}

impl NifAttributes {
pub fn parse(&mut self, meta: ParseNestedMeta) -> syn::parse::Result<()> {
if meta.path.is_ident("schedule") {
let schedule: LitStr = meta.value()?.parse()?;

if VALID_SCHEDULE_OPTIONS.contains(&schedule.value().as_str()) {
self.schedule = Some(schedule);
Ok(())
} else {
Err(meta.error(format!(
"The schedule option is expecting one of the values: {:?}",
VALID_SCHEDULE_OPTIONS
)))
}
} else if meta.path.is_ident("name") {
self.custom_name = Some(meta.value()?.parse()?);
Ok(())
} else {
Err(meta.error("Unsupported nif macro attribute. Expecting schedule or name."))
}
}
}

pub fn transcoder_decorator(nif_attributes: NifAttributes, fun: syn::ItemFn) -> TokenStream {
let sig = &fun.sig;
let name = &sig.ident;
let inputs = &sig.inputs;

let flags = schedule_flag(schedule);
let flags = schedule_flag(nif_attributes.schedule);
let function = fun.to_owned().into_token_stream();
let arity = arity(inputs.clone());
let decoded_terms = extract_inputs(inputs.clone());
let argument_names = create_function_params(inputs.clone());
let erl_func_name = custom_name
let erl_func_name = nif_attributes
.custom_name
.map(|n| syn::Ident::new(n.value().as_str(), Span::call_site()))
.unwrap_or_else(|| name.clone());

Expand Down Expand Up @@ -77,22 +106,10 @@ pub fn transcoder_decorator(
fn schedule_flag(schedule: Option<LitStr>) -> TokenStream {
let mut tokens = TokenStream::new();

let valid = ["DirtyCpu", "DirtyIo", "Normal"];

let flag = match schedule {
Some(lit_str) => {
let value = lit_str.value();

if valid.contains(&value.as_str()) {
syn::Ident::new(value.as_str(), Span::call_site())
} else {
panic!("Invalid schedule option `{}`", value);
}
}
None => syn::Ident::new("Normal", Span::call_site()),
};
let flag = schedule.map_or("Normal".into(), |lit_str| lit_str.value());
let flag_ident = syn::Ident::new(&flag, Span::call_site());

tokens.extend(quote! { rustler::SchedulerFlags::#flag });
tokens.extend(quote! { rustler::SchedulerFlags::#flag_ident });
tokens
}

Expand Down
5 changes: 5 additions & 0 deletions rustler_codegen/tests/test.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
#[test]
fn ui() {
let t = trybuild::TestCases::new();
t.compile_fail("tests/ui/*.rs");
}
8 changes: 8 additions & 0 deletions rustler_codegen/tests/ui/nif-macro-unrecognized-attribute.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
use rustler_codegen::nif;

#[nif(scheduler = "DirtyCpu")]
fn add(a: i64, b: i64) -> i64 {
a + b
}

fn main() {}
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
error: Unsupported nif macro attribute. Expecting schedule or name.
--> tests/ui/nif-macro-unrecognized-attribute.rs:3:7
|
3 | #[nif(scheduler = "DirtyCpu")]
| ^^^^^^^^^
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
use rustler_codegen::nif;

#[nif(schedule = "DirtyGPU")]
fn add(a: i64, b: i64) -> i64 {
a + b
}

fn main() {}
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
error: The schedule option is expecting one of the values: ["Normal", "DirtyCpu", "DirtyIo"]
--> tests/ui/nif-macro-wrong-schedule-attribute-value.rs:3:7
|
3 | #[nif(schedule = "DirtyGPU")]
| ^^^^^^^^^^^^^^^^^^^^^