feat(napi-derive): catch_unwind attribute (#1280)

This commit is contained in:
LongYinan 2022-08-19 23:36:36 +08:00 committed by GitHub
parent bc69e15efb
commit b7a3103f0c
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
14 changed files with 64 additions and 8 deletions

View file

@ -129,6 +129,8 @@ jobs:
ls ./examples/napi-compat-mode
- name: Test
run: yarn test --verbose
env:
SKIP_UNWIND_TEST: 1
if: matrix.settings.host == 'macos-latest'
- name: Test
uses: docker://multiarch/alpine:aarch64-latest-stable

View file

@ -32,7 +32,7 @@ const ZIG_PLATFORM_TARGET_MAP = {
// https://github.com/ziglang/zig/issues/1759
// 'x86_64-unknown-freebsd': 'x86_64-freebsd',
'x86_64-apple-darwin': 'x86_64-macos-gnu',
'aarch64-apple-darwin': 'aarch64-macos-gnu',
'aarch64-apple-darwin': 'aarch64-macos',
'aarch64-unknown-linux-gnu': 'aarch64-linux-gnu',
'aarch64-unknown-linux-musl': 'aarch64-linux-musl',
}
@ -48,7 +48,7 @@ function processZigLinkerArgs(platform: string, args: string[]) {
!(arg === '-framework' && args[index + 1] === 'CoreFoundation') &&
!(arg === 'CoreFoundation' && args[index - 1] === '-framework'),
)
newArgs.push('-Wl,"-undefined=dynamic_lookup"', '-dead_strip')
newArgs.push('-Wl,"-undefined=dynamic_lookup"', '-dead_strip', '-lunwind')
return newArgs
}
if (platform.includes('linux')) {
@ -334,7 +334,9 @@ export class BuildCommand extends Command {
}', process.argv.slice(2)), '-target', '${zigTarget}'], { stdio: 'inherit', shell: true })\nwriteFileSync('${linkerWrapper.replaceAll(
'\\',
'/',
)}.args.log', process.argv.slice(2).join(' '))\n\nprocess.exit(status || 0)\n`,
)}.args.log', processZigLinkerArgs('${
triple.raw
}', process.argv.slice(2)).join(' '))\n\nprocess.exit(status || 0)\n`,
{
mode: '777',
},

View file

@ -26,6 +26,7 @@ pub struct NapiFn {
pub writable: bool,
pub enumerable: bool,
pub configurable: bool,
pub catch_unwind: bool,
}
#[derive(Debug, Clone)]

View file

@ -69,6 +69,20 @@ impl TryToTokens for NapiFn {
}
};
let function_call = if self.catch_unwind {
quote! {
{
std::panic::catch_unwind(|| { #function_call })
.map_err(|e| napi::Error::new(napi::Status::GenericFailure, format!("{:?}", e)))
.and_then(|r| r)
}
}
} else {
quote! {
#function_call
}
};
(quote! {
#(#attrs)*
#[doc(hidden)]

View file

@ -42,6 +42,7 @@ pub struct BindgenAttrs {
macro_rules! attrgen {
($mac:ident) => {
$mac! {
(catch_unwind, CatchUnwind(Span)),
(js_name, JsName(Span, String, Span)),
(constructor, Constructor(Span)),
(factory, Factory(Span)),

View file

@ -695,6 +695,7 @@ fn napi_fn_from_decl(
writable: opts.writable(),
enumerable: opts.enumerable(),
configurable: opts.configurable(),
catch_unwind: opts.catch_unwind().is_some(),
}
})
}
@ -747,6 +748,12 @@ impl ParseNapi for syn::ItemStruct {
"#[napi(return_if_invalid)] can only be applied to a function or method."
);
}
if opts.catch_unwind().is_some() {
bail_span!(
self,
"#[napi(catch_unwind)] can only be applied to a function or method."
);
}
if opts.object().is_some() && opts.custom_finalize().is_some() {
bail_span!(self, "Custom finalize is not supported for #[napi(object)]");
}
@ -776,6 +783,12 @@ impl ParseNapi for syn::ItemImpl {
"#[napi(return_if_invalid)] can only be applied to a function or method."
);
}
if opts.catch_unwind().is_some() {
bail_span!(
self,
"#[napi(catch_unwind)] can only be applied to a function or method."
);
}
// #[napi] macro will be remove from impl items after converted to ast
let napi = self.convert_to_ast(opts);
self.to_tokens(tokens);
@ -802,6 +815,12 @@ impl ParseNapi for syn::ItemEnum {
"#[napi(return_if_invalid)] can only be applied to a function or method."
);
}
if opts.catch_unwind().is_some() {
bail_span!(
self,
"#[napi(catch_unwind)] can only be applied to a function or method."
);
}
let napi = self.convert_to_ast(opts);
self.to_tokens(tokens);
@ -826,6 +845,12 @@ impl ParseNapi for syn::ItemConst {
"#[napi(return_if_invalid)] can only be applied to a function or method."
);
}
if opts.catch_unwind().is_some() {
bail_span!(
self,
"#[napi(catch_unwind)] can only be applied to a function or method."
);
}
let napi = self.convert_to_ast(opts);
self.to_tokens(tokens);
napi

View file

@ -38,7 +38,7 @@ impl<T> PersistedSingleThreadVec<T> {
.inner
.lock()
.expect("Acquire persisted thread vec lock failed");
f(&mut *locked);
f(&mut locked);
}
fn push(&self, item: T) {

View file

@ -854,7 +854,7 @@ impl Env {
))?;
let type_id = unknown_tagged_object as *const TypeId;
if *type_id == TypeId::of::<T>() {
Box::from_raw(unknown_tagged_object as *mut TaggedObject<T>);
drop(Box::from_raw(unknown_tagged_object as *mut TaggedObject<T>));
Ok(())
} else {
Err(Error::new(

View file

@ -103,6 +103,7 @@ Generated by [AVA](https://avajs.dev).
}␊
export function enumToI32(e: CustomNumEnum): number␊
export function throwError(): void␊
export function panic(): void␊
export function createExternal(size: number): ExternalObject<number>
export function createExternalString(content: string): ExternalObject<string>
export function getExternal(external: ExternalObject<number>): number␊

View file

@ -31,6 +31,7 @@ import {
mapOption,
readFile,
throwError,
panic,
readPackageJson,
getPackageJsonName,
getBuffer,
@ -163,7 +164,7 @@ test('enum', (t) => {
t.is(enumToI32(CustomNumEnum.Eight), 8)
})
test.only('class', (t) => {
test('class', (t) => {
const dog = new Animal(Kind.Dog, '旺财')
t.is(dog.name, '旺财')
@ -371,6 +372,9 @@ test('Option', (t) => {
test('Result', (t) => {
t.throws(() => throwError(), void 0, 'Manual Error')
if (!process.env.SKIP_UNWIND_TEST) {
t.throws(() => panic(), void 0, `Don't panic`)
}
})
test('function ts type override', (t) => {

View file

@ -93,6 +93,7 @@ export const enum CustomNumEnum {
}
export function enumToI32(e: CustomNumEnum): number
export function throwError(): void
export function panic(): void
export function createExternal(size: number): ExternalObject<number>
export function createExternalString(content: string): ExternalObject<string>
export function getExternal(external: ExternalObject<number>): number

View file

@ -1,6 +1,11 @@
use napi::bindgen_prelude::*;
#[napi]
fn throw_error() -> Result<()> {
pub fn throw_error() -> Result<()> {
Err(Error::new(Status::InvalidArg, "Manual Error".to_owned()))
}
#[napi(catch_unwind)]
pub fn panic() {
panic!("Don't panic");
}

View file

@ -1,6 +1,6 @@
#![allow(dead_code)]
#![allow(unreachable_code)]
#![allow(clippy::blacklisted_name)]
#![allow(clippy::disallowed_names)]
#[macro_use]
extern crate napi_derive;