Skip to content

Commit

Permalink
feat(napi-derive): catch_unwind attribute (napi-rs#1280)
Browse files Browse the repository at this point in the history
  • Loading branch information
Brooooooklyn authored and h-a-n-a committed Aug 30, 2022
1 parent 39e49a3 commit 6a7730f
Show file tree
Hide file tree
Showing 14 changed files with 64 additions and 8 deletions.
2 changes: 2 additions & 0 deletions .github/workflows/zig.yaml
Expand Up @@ -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
Expand Down
8 changes: 5 additions & 3 deletions cli/src/build.ts
Expand Up @@ -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',
}
Expand All @@ -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')) {
Expand Down Expand Up @@ -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',
},
Expand Down
1 change: 1 addition & 0 deletions crates/backend/src/ast.rs
Expand Up @@ -26,6 +26,7 @@ pub struct NapiFn {
pub writable: bool,
pub enumerable: bool,
pub configurable: bool,
pub catch_unwind: bool,
}

#[derive(Debug, Clone)]
Expand Down
14 changes: 14 additions & 0 deletions crates/backend/src/codegen/fn.rs
Expand Up @@ -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)]
Expand Down
1 change: 1 addition & 0 deletions crates/macro/src/parser/attrs.rs
Expand Up @@ -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)),
Expand Down
25 changes: 25 additions & 0 deletions crates/macro/src/parser/mod.rs
Expand Up @@ -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(),
}
})
}
Expand Down Expand Up @@ -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)]");
}
Expand Down Expand Up @@ -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);
Expand All @@ -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);

Expand All @@ -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
Expand Down
2 changes: 1 addition & 1 deletion crates/napi/src/bindgen_runtime/module_register.rs
Expand Up @@ -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) {
Expand Down
2 changes: 1 addition & 1 deletion crates/napi/src/env.rs
Expand Up @@ -856,7 +856,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(
Expand Down
1 change: 1 addition & 0 deletions examples/napi/__test__/typegen.spec.ts.md
Expand Up @@ -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␊
Expand Down
Binary file modified examples/napi/__test__/typegen.spec.ts.snap
Binary file not shown.
6 changes: 5 additions & 1 deletion examples/napi/__test__/values.spec.ts
Expand Up @@ -31,6 +31,7 @@ import {
mapOption,
readFile,
throwError,
panic,
readPackageJson,
getPackageJsonName,
getBuffer,
Expand Down Expand Up @@ -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, '旺财')
Expand Down Expand Up @@ -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) => {
Expand Down
1 change: 1 addition & 0 deletions examples/napi/index.d.ts
Expand Up @@ -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
Expand Down
7 changes: 6 additions & 1 deletion examples/napi/src/error.rs
@@ -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");
}
2 changes: 1 addition & 1 deletion examples/napi/src/lib.rs
@@ -1,6 +1,6 @@
#![allow(dead_code)]
#![allow(unreachable_code)]
#![allow(clippy::blacklisted_name)]
#![allow(clippy::disallowed_names)]

#[macro_use]
extern crate napi_derive;
Expand Down

0 comments on commit 6a7730f

Please sign in to comment.