Skip to content

Commit

Permalink
fix(cli): always generate typedef file even native code never changes
Browse files Browse the repository at this point in the history
  • Loading branch information
forehalo committed Feb 16, 2023
1 parent 853f52e commit 9daaf60
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 28 deletions.
62 changes: 34 additions & 28 deletions cli/src/build.ts
Original file line number Diff line number Diff line change
Expand Up @@ -289,7 +289,6 @@ export class BuildCommand extends Command {
additionalEnv['XWIN_ARCH'] = 'x86'
}
const cargoCommand = `${cargo} build ${externalFlags}`
const intermediateTypeFile = join(tmpdir(), `type_def.${Date.now()}.tmp`)
debug(`Run ${chalk.green(cargoCommand)}`)

const rustflags = process.env.RUSTFLAGS
Expand Down Expand Up @@ -439,32 +438,7 @@ export class BuildCommand extends Command {
PATH: `${ANDROID_NDK_LATEST_HOME}/toolchains/llvm/prebuilt/linux-x86_64/bin:${process.env.PATH}`,
})
}
try {
execSync(cargoCommand, {
env: {
...process.env,
...additionalEnv,
TYPE_DEF_TMP_PATH: intermediateTypeFile,
},
stdio: 'inherit',
cwd,
})
} catch (e) {
if (cargo === 'cargo-xwin') {
console.warn(
`You are cross compiling ${chalk.underline(
triple.raw,
)} target on ${chalk.green(process.platform)} host`,
)
} else if (isCrossForLinux || isCrossForMacOS) {
console.warn(
`You are cross compiling ${chalk.underline(
triple.raw,
)} on ${chalk.green(process.platform)} host`,
)
}
throw e
}

const { binaryName, packageName } = getNapiConfig(this.configFileName)
let cargoArtifactName = this.cargoName
if (!cargoArtifactName) {
Expand Down Expand Up @@ -494,6 +468,39 @@ export class BuildCommand extends Command {
debug(`Dylib name: ${chalk.greenBright(cargoArtifactName)}`)
}

const intermediateTypeFile = join(
tmpdir(),
`${cargoArtifactName}.napi_type_def.tmp`,
)
debug(`intermediate type def file: ${intermediateTypeFile}`)

try {
execSync(cargoCommand, {
env: {
...process.env,
...additionalEnv,
TYPE_DEF_TMP_PATH: intermediateTypeFile,
},
stdio: 'inherit',
cwd,
})
} catch (e) {
if (cargo === 'cargo-xwin') {
console.warn(
`You are cross compiling ${chalk.underline(
triple.raw,
)} target on ${chalk.green(process.platform)} host`,
)
} else if (isCrossForLinux || isCrossForMacOS) {
console.warn(
`You are cross compiling ${chalk.underline(
triple.raw,
)} on ${chalk.green(process.platform)} host`,
)
}
throw e
}

const platform = triple.platform
let libExt = ''

Expand Down Expand Up @@ -787,7 +794,6 @@ async function processIntermediateTypeFile(
}\n`
: ''

await unlinkAsync(source)
await writeFileAsync(
target,
dtsHeader + externalDef + topLevelDef + namespaceDefs,
Expand Down
26 changes: 26 additions & 0 deletions crates/macro/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ extern crate quote;

#[cfg(not(feature = "noop"))]
use std::env;
use std::sync::atomic::{AtomicBool, Ordering};
#[cfg(all(feature = "type-def", not(feature = "noop")))]
use std::{
fs,
Expand All @@ -35,6 +36,17 @@ use syn::Item;
#[cfg(feature = "compat-mode")]
use syn::{fold::Fold, parse_macro_input, ItemFn};

/// a flag indicate whether or never at least one `napi` macro has been expanded.
/// ```ignore
/// if BUILT_FLAG
/// .compare_exchange(false, true, Ordering::Acquire, Ordering::Relaxed)
/// .is_ok() {
/// // login on first macro expansion
/// }
///
/// ```
static BUILT_FLAG: AtomicBool = AtomicBool::new(false);

/// ```ignore
/// #[napi]
/// fn test(ctx: CallContext, name: String) {
Expand All @@ -44,6 +56,20 @@ use syn::{fold::Fold, parse_macro_input, ItemFn};
#[cfg(not(feature = "noop"))]
#[proc_macro_attribute]
pub fn napi(attr: RawStream, input: RawStream) -> RawStream {
if BUILT_FLAG
.compare_exchange(false, true, Ordering::Acquire, Ordering::Relaxed)
.is_ok()
{
// logic on first macro expansion
#[cfg(feature = "type-def")]
if let Ok(type_def_file) = env::var("TYPE_DEF_TMP_PATH") {
println!("type def file: {:?}", type_def_file);
if let Err(e) = fs::remove_file(type_def_file) {
println!("Failed to manipulate type def file: {:?}", e);
}
}
}

match expand(attr.into(), input.into()) {
Ok(tokens) => {
if env::var("DEBUG_GENERATED_CODE").is_ok() {
Expand Down

1 comment on commit 9daaf60

@github-actions
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Benchmark

Benchmark suite Current: 9daaf60 Previous: 853f52e Ratio
noop#napi-rs 63902223 ops/sec (±0.24%) 62667857 ops/sec (±0.18%) 0.98
noop#JavaScript 711081311 ops/sec (±0.11%) 710441767 ops/sec (±0.14%) 1.00
Plus number#napi-rs 18641722 ops/sec (±0.31%) 18777991 ops/sec (±0.94%) 1.01
Plus number#JavaScript 708675843 ops/sec (±0.14%) 708303095 ops/sec (±0.45%) 1.00
Create buffer#napi-rs 375173 ops/sec (±9.65%) 380066 ops/sec (±8.13%) 1.01
Create buffer#JavaScript 1943144 ops/sec (±6.87%) 1965375 ops/sec (±6.94%) 1.01
createArray#createArrayJson 40430 ops/sec (±0.13%) 40434 ops/sec (±0.12%) 1.00
createArray#create array for loop 7435 ops/sec (±0.11%) 7395 ops/sec (±0.1%) 0.99
createArray#create array with serde trait 7436 ops/sec (±0.11%) 7388 ops/sec (±0.15%) 0.99
getArrayFromJs#get array from json string 16563 ops/sec (±0.12%) 16823 ops/sec (±0.38%) 1.02
getArrayFromJs#get array from serde 10087 ops/sec (±0.03%) 10352 ops/sec (±0.02%) 1.03
getArrayFromJs#get array with for loop 12553 ops/sec (±0.03%) 12478 ops/sec (±0.02%) 0.99
Get Set property#Get Set from native#u32 456308 ops/sec (±7.92%) 468107 ops/sec (±7.26%) 1.03
Get Set property#Get Set from JavaScript#u32 395228 ops/sec (±9.3%) 386123 ops/sec (±9.67%) 0.98
Get Set property#Get Set from native#string 414867 ops/sec (±14.71%) 424293 ops/sec (±14.78%) 1.02
Get Set property#Get Set from JavaScript#string 396114 ops/sec (±3.14%) 395800 ops/sec (±2.91%) 1.00
Async task#spawn task 36412 ops/sec (±2.54%) 37161 ops/sec (±1.22%) 1.02
Async task#ThreadSafeFunction 2107 ops/sec (±13.36%) 2879 ops/sec (±8.58%) 1.37
Async task#Tokio future to Promise 31028 ops/sec (±0.68%) 32295 ops/sec (±0.81%) 1.04
Query#query * 100 2058 ops/sec (±1.92%) 2111 ops/sec (±2.15%) 1.03
Query#query * 1 30862 ops/sec (±0.35%) 31642 ops/sec (±0.38%) 1.03

This comment was automatically generated by workflow using github-action-benchmark.

Please sign in to comment.