@@ -18,13 +18,24 @@ export function generateHeader(functions: FunctionDecl[]) {
1818 "#include <node_api.h>" , // Node-API
1919 "#include <stdio.h>" , // fprintf()
2020 "#include <stdlib.h>" , // abort()
21+ "" ,
22+ // Ideally we would have just used NAPI_NO_RETURN, but
23+ // __declspec(noreturn) (when building with Microsoft Visual C++) cannot be used on members of a struct
24+ // TODO: If we targeted C++23 we could use std::unreachable()
25+ "#if defined(__GNUC__)" ,
26+ "#define WEAK_NODE_API_UNREACHABLE __builtin_unreachable();" ,
27+ "#else" ,
28+ "#define WEAK_NODE_API_UNREACHABLE __assume(0);" ,
29+ "#endif" ,
30+ "" ,
2131 // Generate the struct of function pointers
2232 "struct WeakNodeApiHost {" ,
23- ...functions . map (
24- ( { returnType, noReturn, name, argumentTypes } ) =>
25- `${ returnType } ${
26- noReturn ? " __attribute__((noreturn))" : ""
27- } (*${ name } )(${ argumentTypes . join ( ", " ) } );`,
33+ ...functions . map ( ( { returnType, name, argumentTypes } ) =>
34+ [
35+ returnType ,
36+ // Signature
37+ `(*${ name } )(${ argumentTypes . join ( ", " ) } );` ,
38+ ] . join ( " " ) ,
2839 ) ,
2940 "};" ,
3041 "typedef void(*InjectHostFunction)(const WeakNodeApiHost&);" ,
@@ -46,25 +57,26 @@ export function generateSource(functions: FunctionDecl[]) {
4657 "};" ,
4758 `` ,
4859 // Generate function calling into the host
49- ...functions . flatMap ( ( { returnType, noReturn , name, argumentTypes } ) => {
60+ ...functions . flatMap ( ( { returnType, name, argumentTypes, noReturn } ) => {
5061 return [
51- `extern "C" ${ returnType } ${
52- noReturn ? " __attribute__((noreturn))" : ""
53- } ${ name } (${ argumentTypes
54- . map ( ( type , index ) => `${ type } arg${ index } ` )
55- . join ( ", " ) } ) {`,
62+ 'extern "C"' ,
63+ returnType ,
64+ name ,
65+ "(" ,
66+ argumentTypes . map ( ( type , index ) => `${ type } arg${ index } ` ) . join ( ", " ) ,
67+ ") {" ,
5668 `if (g_host.${ name } == nullptr) {` ,
5769 ` fprintf(stderr, "Node-API function '${ name } ' called before it was injected!\\n");` ,
5870 " abort();" ,
5971 "}" ,
60- ( returnType === "void" ? "" : "return " ) +
61- " g_host." +
62- name +
63- "(" +
64- argumentTypes . map ( ( _ , index ) => `arg ${ index } ` ) . join ( ", " ) +
65- "); ",
72+ returnType === "void" ? "" : "return " ,
73+ ` g_host.${ name } ` ,
74+ "(" ,
75+ argumentTypes . map ( ( _ , index ) => `arg ${ index } ` ) . join ( ", " ) ,
76+ ");" ,
77+ noReturn ? "WEAK_NODE_API_UNREACHABLE" : " ",
6678 "};" ,
67- ] ;
79+ ] . join ( " " ) ;
6880 } ) ,
6981 ] . join ( "\n" ) ;
7082}
0 commit comments