fix(napi-derive): bail the unexpected factory directive (#2051)

- Close https://github.com/napi-rs/napi-rs/issues/2048
This commit is contained in:
LongYinan 2024-04-18 00:14:00 +08:00 committed by GitHub
parent 8f5d7e5274
commit 22c751ced0
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
5 changed files with 32 additions and 4 deletions

View file

@ -559,7 +559,7 @@ fn napi_fn_from_decl(
}
};
Diagnostic::from_vec(errors).map(|_| {
Diagnostic::from_vec(errors).and_then(|_| {
let js_name = if let Some(prop_name) = opts.getter() {
opts.js_name().map_or_else(
|| {
@ -611,7 +611,16 @@ fn napi_fn_from_decl(
false
};
NapiFn {
let kind = fn_kind(opts);
if !matches!(kind, FnKind::Normal) && parent.is_none() {
bail_span!(
sig.ident,
"Only fn in impl block can be marked as factory, constructor, getter or setter"
);
}
Ok(NapiFn {
name: ident.clone(),
js_name,
args,
@ -619,7 +628,7 @@ fn napi_fn_from_decl(
is_ret_result,
is_async: asyncness.is_some(),
vis,
kind: fn_kind(opts),
kind,
fn_self,
parent: parent.cloned(),
comments: extract_doc_comments(&attrs),
@ -638,7 +647,7 @@ fn napi_fn_from_decl(
catch_unwind: opts.catch_unwind().is_some(),
unsafe_: sig.unsafety.is_some(),
register_name: get_register_ident(ident.to_string().as_str()),
}
})
})
}

View file

@ -0,0 +1,12 @@
//! This is testing that `#[napi(factory)]` outside of an `impl` block fails
use napi_derive::napi;
#[napi(factory)]
pub fn add() {
println!("Hello, world!");
}
// Needed for the trybuild tests.
#[allow(unused)]
fn main() {}

View file

@ -0,0 +1,5 @@
error: Only fn in impl block can be marked as factory, constructor, getter or setter
--> tests/build_error_tests/fn_outside_impl_factory.rs:6:8
|
6 | pub fn add() {
| ^^^

View file

@ -1,5 +1,6 @@
//! Include the test files here so they can be formatted properly with `cargo fmt`
pub mod fn_outside_impl_factory;
pub mod ts_arg_type_1;
pub mod ts_arg_type_2;
pub mod ts_arg_type_3;

View file

@ -8,4 +8,5 @@ mod build_error_tests;
fn run_build_error_tests() {
let t = trybuild::TestCases::new();
t.compile_fail("tests/build_error_tests/ts_arg_type_*.rs");
t.compile_fail("tests/build_error_tests/fn_outside_impl_factory.rs");
}