Skip to main content

hydro_lang/compile/trybuild/
generate.rs

1use std::fs::{self, File};
2use std::io::{Read, Seek, SeekFrom, Write};
3use std::path::{Path, PathBuf};
4
5#[cfg(any(feature = "deploy", feature = "maelstrom"))]
6use dfir_lang::diagnostic::Diagnostics;
7#[cfg(any(feature = "deploy", feature = "maelstrom"))]
8use dfir_lang::graph::{AsCodeOptions, DfirGraph};
9use sha2::{Digest, Sha256};
10#[cfg(any(feature = "deploy", feature = "maelstrom"))]
11use stageleft::internal::quote;
12use trybuild_internals_api::cargo::{self, Metadata};
13use trybuild_internals_api::env::Update;
14use trybuild_internals_api::normalize::Normalization;
15use trybuild_internals_api::run::{PathDependency, Project};
16use trybuild_internals_api::{Runner, dependencies, features, path};
17
18pub const HYDRO_RUNTIME_FEATURES: &[&str] = &[
19    "deploy_integration",
20    "runtime_measure",
21    "docker_runtime",
22    "ecs_runtime",
23    "maelstrom_runtime",
24    "sim_runtime",
25];
26
27#[cfg(any(feature = "deploy", feature = "maelstrom"))]
28/// Whether to use dynamic linking for the generated binary.
29/// - `Static`: Place in base crate examples (for remote/containerized deploys)
30/// - `Dynamic`: Place in dylib crate examples (for sim and localhost deploys)
31#[derive(Debug, Clone, Copy, PartialEq, Eq)]
32pub enum LinkingMode {
33    // `Static` is only constructed by the deploy backends; Maelstrom-only builds
34    // always use `Dynamic`.
35    #[cfg_attr(
36        not(feature = "deploy"),
37        expect(
38            dead_code,
39            reason = "only constructed by the deploy backends; Maelstrom-only builds use Dynamic"
40        )
41    )]
42    Static,
43    #[cfg(any(feature = "deploy", feature = "maelstrom"))]
44    Dynamic,
45}
46
47#[cfg(any(feature = "deploy", feature = "maelstrom"))]
48/// The deployment mode for code generation.
49#[derive(Debug, Clone, Copy, PartialEq, Eq)]
50pub enum DeployMode {
51    #[cfg(feature = "deploy")]
52    /// Standard `HydroDeploy`
53    HydroDeploy,
54    #[cfg(any(feature = "docker_deploy", feature = "ecs_deploy"))]
55    /// Containerized deployment (Docker/ECS)
56    Containerized,
57    #[cfg(feature = "maelstrom")]
58    /// Maelstrom deployment with stdin/stdout JSON protocol
59    Maelstrom,
60}
61
62pub(crate) static IS_TEST: std::sync::atomic::AtomicBool =
63    std::sync::atomic::AtomicBool::new(false);
64
65pub(crate) static CONCURRENT_TEST_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
66
67/// Enables "test mode" for Hydro, which makes it possible to compile Hydro programs written
68/// inside a `#[cfg(test)]` module. This should be enabled in a global [`ctor`] hook.
69///
70/// # Example
71/// ```ignore
72/// #[cfg(test)]
73/// mod test_init {
74///    #[ctor::ctor]
75///    fn init() {
76///        hydro_lang::compile::init_test();
77///    }
78/// }
79/// ```
80pub fn init_test() {
81    IS_TEST.store(true, std::sync::atomic::Ordering::Relaxed);
82}
83
84#[cfg(any(feature = "deploy", feature = "maelstrom"))]
85fn clean_bin_name_prefix(bin_name_prefix: &str) -> String {
86    bin_name_prefix
87        .replace("::", "__")
88        .replace([' ', ',', '<', '{', '}'], "_")
89        .replace(['>', '(', ')'], "")
90}
91
92#[derive(Debug, Clone)]
93pub struct TrybuildConfig {
94    pub project_dir: PathBuf,
95    pub target_dir: PathBuf,
96    /// The cargo package name of the generated project's `dylib` crate, which the dynamically
97    /// linked examples (sim and localhost deploys) load at runtime.
98    pub dylib_package_name: String,
99    pub features: Option<Vec<String>>,
100    #[cfg(any(feature = "deploy", feature = "maelstrom"))]
101    // Only the deploy backends read this field; Maelstrom-only builds derive the
102    // linking behavior directly.
103    #[cfg_attr(
104        not(feature = "deploy"),
105        expect(dead_code, reason = "only read by the deploy backends")
106    )]
107    /// Which crate within the workspace to use for examples.
108    /// - `Static`: base crate (for remote/containerized deploys)
109    /// - `Dynamic`: dylib-examples crate (for sim and localhost deploys)
110    pub linking_mode: LinkingMode,
111}
112
113#[cfg(any(feature = "deploy", feature = "maelstrom"))]
114pub fn create_graph_trybuild(
115    graph: DfirGraph,
116    extra_stmts: &[syn::Stmt],
117    sidecars: &[syn::Expr],
118    as_code_options: &AsCodeOptions,
119    bin_name_prefix: Option<&str>,
120    deploy_mode: DeployMode,
121    linking_mode: LinkingMode,
122) -> (String, TrybuildConfig) {
123    let source_dir = cargo::manifest_dir().unwrap();
124    let source_manifest = dependencies::get_manifest(&source_dir).unwrap();
125    let crate_name = source_manifest.package.name.replace('-', "_");
126
127    let is_test = IS_TEST.load(std::sync::atomic::Ordering::Relaxed);
128
129    let generated_code = {
130        let _span = tracing::debug_span!(target: "hydro_build", "graph_codegen").entered();
131        compile_graph_trybuild(
132            graph,
133            extra_stmts,
134            sidecars,
135            as_code_options,
136            &crate_name,
137            deploy_mode,
138        )
139    };
140
141    let source = {
142        let _span = tracing::debug_span!(target: "hydro_build", "unparse_source").entered();
143        prettyplease::unparse(&generated_code)
144    };
145
146    let hash = format!("{:X}", Sha256::digest(&source))
147        .chars()
148        .take(8)
149        .collect::<String>();
150
151    let bin_name = if let Some(bin_name_prefix) = bin_name_prefix {
152        format!("{}_{}", clean_bin_name_prefix(bin_name_prefix), hash)
153    } else {
154        hash
155    };
156
157    let (project_dir, target_dir, dylib_package_name, mut cur_bin_enabled_features) =
158        create_trybuild().unwrap();
159
160    // Determine which crate's examples folder to use based on linking mode
161    let examples_dir = match linking_mode {
162        LinkingMode::Static => path!(project_dir / "examples"),
163        #[cfg(any(feature = "deploy", feature = "maelstrom"))]
164        LinkingMode::Dynamic => path!(project_dir / "dylib-examples" / "examples"),
165    };
166
167    // TODO(shadaj): garbage collect this directory occasionally
168    fs::create_dir_all(&examples_dir).unwrap();
169
170    let out_path = path!(examples_dir / format!("{bin_name}.rs"));
171    {
172        let _span =
173            tracing::debug_span!(target: "hydro_build", "write_generated_sources").entered();
174        let _concurrent_test_lock = CONCURRENT_TEST_LOCK.lock().unwrap();
175        write_atomic(source.as_ref(), &out_path).unwrap();
176    }
177
178    if is_test {
179        write_staged_source_cached(source_dir.as_ref(), &crate_name, &project_dir);
180    }
181
182    if is_test {
183        if cur_bin_enabled_features.is_none() {
184            cur_bin_enabled_features = Some(vec![]);
185        }
186
187        cur_bin_enabled_features
188            .as_mut()
189            .unwrap()
190            .push("hydro___test".to_owned());
191    }
192
193    (
194        bin_name,
195        TrybuildConfig {
196            project_dir,
197            target_dir,
198            dylib_package_name,
199            features: cur_bin_enabled_features,
200            #[cfg(any(feature = "deploy", feature = "maelstrom"))]
201            linking_mode,
202        },
203    )
204}
205
206#[cfg(any(feature = "deploy", feature = "maelstrom"))]
207pub fn compile_graph_trybuild(
208    partitioned_graph: DfirGraph,
209    extra_stmts: &[syn::Stmt],
210    sidecars: &[syn::Expr],
211    as_code_options: &AsCodeOptions,
212    crate_name: &str,
213    deploy_mode: DeployMode,
214) -> syn::File {
215    use crate::staging_util::get_this_crate;
216
217    let mut diagnostics = Diagnostics::new();
218    let dfir_expr: syn::Expr = syn::parse2(
219        partitioned_graph
220            .as_code_with_options(
221                &quote! { __root_dfir_rs },
222                as_code_options,
223                quote!(),
224                &mut diagnostics,
225            )
226            .expect("DFIR code generation failed with diagnostics."),
227    )
228    .unwrap();
229
230    let orig_crate_name = quote::format_ident!("{}", crate_name);
231    let trybuild_crate_name_ident = quote::format_ident!("{}_hydro_trybuild", crate_name);
232    let root = get_this_crate();
233    let tokio_main_ident = format!("{}::runtime_support::tokio", root);
234    let dfir_ident = quote::format_ident!("{}", crate::compile::DFIR_IDENT);
235
236    let source_ast: syn::File = match deploy_mode {
237        #[cfg(any(feature = "docker_deploy", feature = "ecs_deploy"))]
238        DeployMode::Containerized => {
239            syn::parse_quote! {
240                #![allow(unused_imports, unused_crate_dependencies, missing_docs, non_snake_case, unexpected_cfgs, unfulfilled_lint_expectations)]
241                use #trybuild_crate_name_ident::__root as #orig_crate_name;
242                use #orig_crate_name::*;
243                use #orig_crate_name::__staged::__deps::*;
244                use #root::prelude::*;
245                use #root::runtime_support::dfir_rs as __root_dfir_rs;
246                pub use #orig_crate_name::__staged;
247
248                #[#root::runtime_support::tokio::main(crate = #tokio_main_ident, flavor = "current_thread")]
249                async fn main() {
250                    #root::telemetry::initialize_tracing();
251
252                    #( #extra_stmts )*
253
254                    let mut #dfir_ident = #dfir_expr;
255
256                    #(
257                        let _ = #root::runtime_support::tokio::spawn( #sidecars ); // Uses #dfir_ident
258                    )*
259
260                    let _ = #dfir_ident.run().await;
261                }
262            }
263        }
264        #[cfg(feature = "deploy")]
265        DeployMode::HydroDeploy => {
266            syn::parse_quote! {
267                #![allow(unused_imports, unused_crate_dependencies, missing_docs, non_snake_case, unexpected_cfgs, unfulfilled_lint_expectations)]
268                use #trybuild_crate_name_ident::__root as #orig_crate_name;
269                use #orig_crate_name::*;
270                use #orig_crate_name::__staged::__deps::*;
271                use #root::prelude::*;
272                use #root::runtime_support::dfir_rs as __root_dfir_rs;
273                pub use #orig_crate_name::__staged;
274
275                #[#root::runtime_support::tokio::main(crate = #tokio_main_ident, flavor = "current_thread")]
276                async fn main() {
277                    let __hydro_lang_trybuild_cli_owned: #root::runtime_support::hydro_deploy_integration::DeployPorts<#root::__staged::deploy::deploy_runtime::HydroMeta> = #root::runtime_support::launch::init_no_ack_start().await;
278                    let __hydro_lang_trybuild_cli = &__hydro_lang_trybuild_cli_owned;
279
280                    #( #extra_stmts )*
281
282                    let mut #dfir_ident = #dfir_expr;
283                    println!("ack start");
284
285                    // TODO(mingwei): initialize `tracing` at this point in execution.
286                    // After "ack start" is when we can print whatever we want.
287
288                    #(
289                        let _ = #root::runtime_support::tokio::spawn( #sidecars ); // Uses #dfir_ident
290                    )*
291
292                    let _ = #root::runtime_support::launch::run_stdin_commands(
293                        async move {
294                            #dfir_ident.run().await
295                        }
296                    ).await;
297                }
298            }
299        }
300        #[cfg(feature = "maelstrom")]
301        DeployMode::Maelstrom => {
302            // The `MetricsState` typestate of the generated `Dfir`, revealed in the
303            // `impl TickClosure` signature so sidecars can call `.metrics()` when tracking is enabled.
304            let dfir_metrics_ty = crate::compile::dfir_metrics_state_type(as_code_options, &root);
305            syn::parse_quote! {
306                #![allow(unused_imports, unused_crate_dependencies, missing_docs, non_snake_case, unexpected_cfgs, unfulfilled_lint_expectations)]
307                use #trybuild_crate_name_ident::__root as #orig_crate_name;
308                use #orig_crate_name::*;
309                use #orig_crate_name::__staged::__deps::*;
310                use #root::prelude::*;
311                use #root::runtime_support::dfir_rs as __root_dfir_rs;
312                pub use #orig_crate_name::__staged;
313
314                #[allow(unused)]
315                fn __hydro_runtime<'a>(
316                    __hydro_lang_maelstrom_meta: &'a #root::__staged::deploy::maelstrom::deploy_runtime_maelstrom::MaelstromMeta
317                )
318                    -> #root::runtime_support::dfir_rs::scheduled::context::Dfir<impl #root::runtime_support::dfir_rs::scheduled::context::TickClosure<Metrics = #dfir_metrics_ty> + 'a>
319                {
320                    #( #extra_stmts )*
321
322                    #dfir_expr
323                }
324
325                #[#root::runtime_support::tokio::main(crate = #tokio_main_ident, flavor = "current_thread")]
326                async fn main() {
327                    #root::telemetry::initialize_tracing();
328
329                    // Initialize Maelstrom protocol - read init message and send init_ok
330                    let __hydro_lang_maelstrom_meta = #root::__staged::deploy::maelstrom::deploy_runtime_maelstrom::maelstrom_init();
331
332                    let mut #dfir_ident = __hydro_runtime(&__hydro_lang_maelstrom_meta);
333
334                    __hydro_lang_maelstrom_meta.start_receiving(); // start receiving messages after initializing subscribers
335
336                    #(
337                        let _ = #root::runtime_support::tokio::spawn( #sidecars ); // Uses #dfir_ident
338                    )*
339
340                    let _ = #dfir_ident.run().await;
341                }
342            }
343        }
344    };
345    source_ast
346}
347
348/// Configuration for [`compile_trybuild_example`], the shared concurrent-build
349/// entrypoint used by both the simulator and the Maelstrom deployment target.
350#[cfg(any(feature = "sim", feature = "maelstrom"))]
351pub struct ExampleBuildConfig<'a> {
352    /// The trybuild project + target directories and enabled features.
353    pub trybuild: TrybuildConfig,
354    /// The generated example base name (a content hash). Used as the per-job
355    /// directory name and, when [`Self::set_trybuild_lib_name`] is set, as the
356    /// value of the `TRYBUILD_LIB_NAME` environment variable.
357    pub bin_name: String,
358    /// A runtime feature to enable in addition to [`TrybuildConfig::features`]
359    /// (e.g. `hydro___feature_sim_runtime` or `hydro___feature_maelstrom_runtime`).
360    pub runtime_feature: &'a str,
361    /// The cargo `--example` target to build. For the simulator this is the
362    /// fixed `sim-dylib` wrapper; for Maelstrom it is the generated `bin_name`.
363    pub example_name: String,
364    /// If `Some`, override the crate type on the command line (e.g. `cdylib`
365    /// for the simulator). `None` builds a normal executable example.
366    pub crate_type: Option<&'a str>,
367    /// Whether to set `TRYBUILD_LIB_NAME` to `bin_name` (the simulator uses this
368    /// for its `include!`-based indirection).
369    pub set_trybuild_lib_name: bool,
370}
371
372/// Returns the toolchain's target libdir (where the shared `libstd` lives), memoized.
373#[cfg(any(feature = "sim", feature = "maelstrom"))]
374fn rustc_target_libdir() -> Option<String> {
375    static LIBDIR: std::sync::OnceLock<Option<String>> = std::sync::OnceLock::new();
376    LIBDIR
377        .get_or_init(|| {
378            let rustc = std::env::var("RUSTC").unwrap_or_else(|_| "rustc".to_owned());
379            std::process::Command::new(rustc)
380                .args(["--print", "target-libdir"])
381                .output()
382                .ok()
383                .filter(|out| out.status.success())
384                .map(|out| String::from_utf8(out.stdout).unwrap().trim().to_owned())
385        })
386        .clone()
387}
388
389/// The rustflags this crate was compiled with, in cargo's `CARGO_ENCODED_RUSTFLAGS` encoding,
390/// captured by `build.rs`. See [`forward_rustflags`]. Also keys the trybuild dylib's target name
391/// (see [`create_trybuild`]).
392const ENCODED_RUSTFLAGS: &str = env!("HYDRO_ENCODED_RUSTFLAGS");
393
394/// The triple the child `cargo` compiles for: `CARGO_BUILD_TARGET` from the environment, else
395/// the host.
396#[cfg(any(feature = "sim", feature = "maelstrom"))]
397fn child_target_triple() -> String {
398    static HOST: std::sync::OnceLock<String> = std::sync::OnceLock::new();
399    std::env::var("CARGO_BUILD_TARGET").unwrap_or_else(|_| {
400        HOST.get_or_init(|| {
401            let rustc = std::env::var("RUSTC").unwrap_or_else(|_| "rustc".to_owned());
402            let out = std::process::Command::new(rustc)
403                .arg("-vV")
404                .output()
405                .expect("failed to run `rustc -vV`");
406            String::from_utf8(out.stdout)
407                .unwrap()
408                .lines()
409                .find_map(|line| line.strip_prefix("host: "))
410                .expect("`rustc -vV` did not report a host triple")
411                .to_owned()
412        })
413        .clone()
414    })
415}
416
417/// Passes the rustflags this crate was compiled with to the child `cargo` compiling a generated
418/// program, so it gets the same `--cfg`s, instrumentation and codegen options.
419///
420/// Tests may be run with rustflags from cargo config (`--config`, `build.rustflags`,
421/// `target.*.rustflags`), which are not in the test process's environment. Cargo exposes the
422/// resolved flags to build scripts as `CARGO_ENCODED_RUSTFLAGS`, so `build.rs` bakes them into
423/// [`ENCODED_RUSTFLAGS`].
424///
425/// The child gets them as `--config target.<triple>.rustflags=[...]`, not as
426/// `CARGO_ENCODED_RUSTFLAGS` in its environment. Build scripts emitting
427/// `rerun-if-env-changed=CARGO_ENCODED_RUSTFLAGS` (e.g. `aws-lc-sys`) are fingerprinted on that
428/// variable in the *cargo process's* environment, not on the value cargo injects into the build
429/// script's. The outer `cargo` has none; a child `cargo` launched with it set would record a
430/// different fingerprint for those crates in the shared `deps/`, and the two builds would rebuild
431/// them back and forth. `target.<triple>.rustflags` is the highest-precedence config key, and the
432/// forwarded flags are cargo's own resolution of the config, so no configured flag is lost.
433#[cfg(any(feature = "sim", feature = "maelstrom"))]
434fn forward_rustflags(command: &mut std::process::Command) {
435    let flags = toml::Value::try_from(
436        ENCODED_RUSTFLAGS
437            .split('\x1f')
438            .filter(|flag| !flag.is_empty())
439            .collect::<Vec<_>>(),
440    )
441    .unwrap();
442    let triple = child_target_triple();
443    command.args(["--config", &format!("target.{triple}.rustflags={flags}")]);
444}
445
446/// Compiles a generated trybuild example against the prebuilt dylib crate,
447/// using the shared parallel-compilation machinery (per-job target dirs with
448/// symlinked shared artifacts, plus a prebuild of the dylib dependencies).
449///
450/// Returns the path of a persistent hard link to the built artifact (a `cdylib`
451/// for the simulator, or an executable for Maelstrom) under the shared target
452/// dir's `debug/deps/hydro-coverage` (`<triple>/debug/...` when building for an
453/// explicit compilation target). Cargo repoints the job's uplifted artifact
454/// on every rebuild, so the caller must not load that path directly; the link is
455/// taken while the job's build lock is still held, so it names exactly the build
456/// this call produced, and a later rebuild (which unlinks and re-links the
457/// uplifted name) leaves it intact. Coverage reporters also find it there (see
458/// the comment at the link site).
459#[cfg(any(feature = "sim", feature = "maelstrom"))]
460pub fn compile_trybuild_example(config: ExampleBuildConfig<'_>) -> Result<PathBuf, ()> {
461    use std::process::{Command, Stdio};
462
463    let ExampleBuildConfig {
464        trybuild,
465        bin_name,
466        runtime_feature,
467        example_name,
468        crate_type,
469        set_trybuild_lib_name,
470    } = config;
471
472    // Run from the dylib-examples crate, which has the dylib as a dependency.
473    let crate_to_compile = path!(trybuild.project_dir / "dylib-examples");
474
475    // With an explicit compilation target (`cargo sim` sets one, see `cargo-sim`) cargo keeps
476    // target artifacts under `<triple>/debug/` and host artifacts under `debug/`; the per-job
477    // dirs mirror both layers.
478    let build_target = std::env::var("CARGO_BUILD_TARGET").ok();
479    let dirs = hydro_concurrent_cargo::ArtifactDirs::new("debug", build_target.as_deref());
480    let shared_debug = trybuild.target_dir.join(&dirs.target);
481
482    let (final_target_dir, _prebuild_guard, _cargo_lock) = {
483        let prebuild_span =
484            tracing::debug_span!(target: "hydro_build", "prebuild", bin_name = %bin_name).entered();
485        let jobs_dir = trybuild.target_dir.join("jobs");
486        let per_job = hydro_concurrent_cargo::setup_job_dir(
487            &jobs_dir,
488            &bin_name,
489            &trybuild.target_dir,
490            &dirs,
491        );
492
493        let mut features: Vec<String> = trybuild.features.clone().unwrap_or_default();
494        features.push(runtime_feature.to_owned());
495
496        let staged_paths = vec![
497            path!(trybuild.project_dir / "src" / "__staged.rs"),
498            path!(trybuild.project_dir / "Cargo.lock"),
499            std::env::current_exe().unwrap(),
500        ];
501
502        let features_for_closure = features.clone();
503
504        // The prebuild is fingerprinted on these features, our rustflags, and the compiler
505        // version: shared artifacts built under other flags or another toolchain are rebuilt
506        // (under the exclusive lock, after renaming the dylib for this configuration) before any
507        // final build links against them.
508        let (guard, cargo_lock) = hydro_concurrent_cargo::run_prebuild(
509            &trybuild.target_dir,
510            &dirs,
511            trybuild.project_dir.file_name().unwrap().to_str().unwrap(),
512            &features,
513            ENCODED_RUSTFLAGS,
514            &staged_paths,
515            |prebuild_target| {
516                hydro_concurrent_cargo::set_dylib_lib_name(
517                    &trybuild.project_dir,
518                    ENCODED_RUSTFLAGS,
519                );
520                let features_str = features_for_closure.join(",");
521
522                // Prebuild the lib that final builds will link against, which transitively
523                // builds the trybuild dylib *as a dependency*. This matters: cargo passes
524                // `-C prefer-dynamic` to dylib crates when they are built as dependencies
525                // (linking libstd dynamically), but *not* when they are the primary build
526                // target — and the two variants share a cargo fingerprint, so whichever is
527                // built first wins. Building the dylib as a primary target would poison the
528                // cache with a statically-linked-std variant that later fails to link into
529                // examples ("cannot satisfy dependencies so `std` only shows up once").
530                let mut lib_cmd = Command::new("cargo");
531                lib_cmd.current_dir(&crate_to_compile);
532                lib_cmd.args(["build", "--locked", "--lib"]);
533                lib_cmd.args(["--target-dir", prebuild_target.to_str().unwrap()]);
534                lib_cmd.arg("--no-default-features");
535                lib_cmd.args(["--features", &features_str]);
536                lib_cmd.args(["--config", "build.incremental = false"]);
537                lib_cmd.env("STAGELEFT_TRYBUILD_BUILD_STAGED", "1");
538                forward_rustflags(&mut lib_cmd);
539                let status = lib_cmd.stdin(Stdio::null()).status().unwrap();
540                assert!(status.success(), "dep prebuild failed")
541            },
542        );
543
544        // Close the prebuild span before returning the guards: the guards are held for the
545        // entire final build, but the prebuild phase (freshness check + possible dep build)
546        // ends here.
547        drop(prebuild_span);
548        (per_job, guard, cargo_lock)
549    };
550
551    // Populate per-job build/ dir right before final build. Hold guard for entire build.
552    let _job_build_guard = {
553        let populate_span =
554            tracing::debug_span!(target: "hydro_build", "populate_job_dir", bin_name = %bin_name)
555                .entered();
556        let guard = hydro_concurrent_cargo::populate_job_build_dir(
557            &final_target_dir,
558            &trybuild.target_dir,
559            &dirs,
560        );
561        // Close the populate span here: the returned guard is held until the final build
562        // finishes, but the population work itself ends here.
563        drop(populate_span);
564        guard
565    };
566
567    let final_build_span =
568        tracing::debug_span!(target: "hydro_build", "final_build", bin_name = %bin_name).entered();
569    let mut command = Command::new("cargo");
570    command.current_dir(&crate_to_compile);
571    command.args(["rustc", "--frozen"]);
572    command.args(["--example", &example_name]);
573    command.args(["--target-dir", final_target_dir.to_str().unwrap()]);
574    // Never enable default features: the generated example gets exactly the
575    // features it needs via `--features` (plus the runtime feature). This keeps
576    // the feature set minimal and deterministic — matching what the deploy
577    // backends and the base trybuild crate (which carries the source crate's
578    // `default`) would otherwise pull in.
579    command.arg("--no-default-features");
580    command.args([
581        "--features",
582        &trybuild
583            .features
584            .clone()
585            .into_iter()
586            .flatten()
587            .chain([runtime_feature.to_owned()])
588            .collect::<Vec<_>>()
589            .join(","),
590    ]);
591    command.args(["--config", "build.incremental = false"]);
592    forward_rustflags(&mut command);
593    if let Some(crate_type) = crate_type {
594        command.args(["--crate-type", crate_type]);
595    }
596    command.arg("--message-format=json-diagnostic-rendered-ansi");
597    command.env("STAGELEFT_TRYBUILD_BUILD_STAGED", "1");
598    if set_trybuild_lib_name {
599        command.env("TRYBUILD_LIB_NAME", &bin_name);
600    }
601
602    command.arg("--");
603
604    // Give this job its own cargo unit. The simulator builds the fixed `sim-dylib` example in
605    // every job, varying only `TRYBUILD_LIB_NAME` — which affects the unit's *freshness* but
606    // not its hash. Cargo folds these extra rustc args into the unit hash, so without a
607    // per-job argument every flow shares one `.fingerprint/` entry and one `deps/` output
608    // (both symlinked to the shared `target/debug/` under the legacy layout) and flows
609    // invalidate each other on every switch: a full relink per test, and the previous flow's
610    // artifact gets replaced while another test process may still have it loaded. (On Linux
611    // and macOS the per-job rpath arguments below happened to do this implicitly.)
612    command.arg(format!("-Cmetadata={bin_name}"));
613
614    if cfg!(any(target_os = "linux", target_os = "macos")) {
615        // The built example links the trybuild dylib dynamically. Bake rpath entries for
616        // where cargo places it (which depends on the build-dir layout, see
617        // `hydro_concurrent_cargo::dylib_search_dirs`) and for the toolchain's shared libstd,
618        // so the artifact can be loaded/run without LD_LIBRARY_PATH.
619        let mut rpaths = hydro_concurrent_cargo::dylib_search_dirs(
620            &trybuild.dylib_package_name,
621            &final_target_dir.join(&dirs.target),
622            &shared_debug,
623        );
624        if let Some(libdir) = rustc_target_libdir() {
625            rpaths.push(PathBuf::from(libdir));
626        }
627        for rpath in rpaths {
628            if cfg!(target_os = "macos") {
629                // On macOS rustc may invoke the linker directly (`rust-lld -flavor darwin`),
630                // which rejects `-Wl,`-wrapped arguments. Use raw ld64 syntax (`-rpath <path>`
631                // as two arguments), which the clang driver also forwards to the linker.
632                command.args([
633                    "-Clink-arg=-rpath".to_owned(),
634                    format!("-Clink-arg={}", rpath.to_str().unwrap()),
635                ]);
636            } else {
637                command.args([format!("-Clink-arg=-Wl,-rpath,{}", rpath.to_str().unwrap())]);
638            }
639        }
640
641        if cfg!(all(target_os = "linux", target_env = "gnu")) {
642            command.arg(
643                // https://github.com/rust-lang/rust/issues/91979
644                "-Clink-args=-Wl,-z,nodelete",
645            );
646        }
647    }
648
649    tracing::debug!(
650        target: "hydro_build",
651        "final build command (cwd={}): {:?}",
652        crate_to_compile.display(),
653        command
654    );
655
656    let mut spawned = command
657        .stdout(Stdio::piped())
658        .stderr(Stdio::piped())
659        .stdin(Stdio::null())
660        .spawn()
661        .unwrap();
662    let reader = std::io::BufReader::new(spawned.stdout.take().unwrap());
663    let stderr_handle = spawned.stderr.take().unwrap();
664    let stderr_thread = std::thread::spawn(move || {
665        use std::io::Read;
666        let mut buf = String::new();
667        std::io::BufReader::new(stderr_handle)
668            .read_to_string(&mut buf)
669            .unwrap();
670        buf
671    });
672
673    let mut out = Err(());
674    for message in cargo_metadata::Message::parse_stream(reader) {
675        match message.unwrap() {
676            cargo_metadata::Message::CompilerArtifact(artifact) => {
677                // unlike dylib, cdylib only exports the explicitly exported symbols
678                let is_output = artifact.target.is_example();
679
680                if is_output {
681                    let path = artifact.filenames.first().unwrap();
682                    let path_buf: PathBuf = path.clone().into();
683                    out = Ok(path_buf);
684                }
685            }
686            cargo_metadata::Message::CompilerMessage(mut msg) => {
687                // Update the path displayed to enable clicking in IDE.
688                // TODO(mingwei): deduplicate code with hydro_deploy rust_crate/build.rs
689                if let Some(rendered) = msg.message.rendered.as_mut() {
690                    let file_names = msg
691                        .message
692                        .spans
693                        .iter()
694                        .map(|s| &s.file_name)
695                        .collect::<std::collections::BTreeSet<_>>();
696                    for file_name in file_names {
697                        *rendered = rendered.replace(
698                            file_name,
699                            &format!("(full path) {}/{file_name}", trybuild.project_dir.display()),
700                        )
701                    }
702                }
703                eprintln!("{}", msg.message);
704            }
705            cargo_metadata::Message::TextLine(line) => {
706                eprintln!("{}", line);
707            }
708            cargo_metadata::Message::BuildFinished(_) => {}
709            cargo_metadata::Message::BuildScriptExecuted(_) => {}
710            msg => panic!("Unexpected message type: {:?}", msg),
711        }
712    }
713
714    spawned.wait().unwrap();
715    let stderr_output = stderr_thread.join().unwrap();
716    drop(final_build_span);
717
718    // Check for unexpected recompilations — only dylib-examples should be compiled.
719    for line in stderr_output.lines() {
720        if line.contains("Compiling") {
721            assert!(
722                line.contains("dylib-examples"),
723                "unexpected recompilation in final build: {line}\nfull stderr:\n{stderr_output}"
724            );
725        }
726    }
727
728    assert!(
729        out.is_ok(),
730        "final build failed to produce binary.\nstderr:\n{stderr_output}"
731    );
732
733    // Hard-link the artifact to a name keyed by the generated source's hash (embedded in
734    // `bin_name`) and by the toolchain fingerprint, under the shared target dir's
735    // `debug/deps`. This is what the caller loads, and it doubles as the artifact coverage
736    // reporters need: the coverage mapping that resolves profile data lives in the artifact
737    // itself, and reporters run only after all test processes have exited, scanning
738    // `target/debug` or `target/debug/deps` recursively (both are common
739    // `grcov --binary-path` conventions). The link is made unconditionally because whether
740    // the artifact is instrumented cannot be told from this crate's own flags: selective
741    // instrumentation may instrument the generated program but not `hydro_lang`.
742    // See https://github.com/hydro-project/hydro/issues/3160.
743    let out = out.unwrap();
744    let coverage_dir = path!(shared_debug / "deps" / "hydro-coverage");
745    fs::create_dir_all(&coverage_dir).unwrap();
746    let artifact_name = out.file_name().unwrap().to_str().unwrap();
747    let fingerprint = hydro_concurrent_cargo::toolchain_fingerprint(ENCODED_RUSTFLAGS);
748    let persisted = path!(coverage_dir / format!("{bin_name}-{fingerprint}-{artifact_name}"));
749
750    // Job dirs are keyed by `bin_name`, so a concurrent test process building the same flow
751    // shares this job. If cargo found that build up to date, `persisted` already links the very
752    // file cargo just reported and there is nothing left to do. Skipping the relink matters on
753    // Windows, where that other process has `persisted` loaded (mapped as an image) and the
754    // `rename` below would fail with "Access is denied".
755    if same_file::is_same_file(&out, &persisted).unwrap_or(false) {
756        return Ok(persisted);
757    }
758
759    // Link under a unique name, then rename over the final one, so concurrent test processes
760    // loading the same flow never observe a missing or partially-written artifact.
761    let staging = path!(
762        coverage_dir
763            / format!(
764                ".{bin_name}.{}.{}.tmp",
765                std::process::id(),
766                std::time::SystemTime::now()
767                    .duration_since(std::time::UNIX_EPOCH)
768                    .unwrap()
769                    .as_nanos()
770            )
771    );
772    if fs::hard_link(&out, &staging).is_err() {
773        // Filesystems without hard links (or a target dir split across devices) still get a
774        // private snapshot of this build, at the cost of a copy.
775        fs::copy(&out, &staging).unwrap();
776    }
777    fs::rename(&staging, &persisted).unwrap_or_else(|err| {
778        // Windows refuses to replace a file that another process has mapped as an image. A
779        // concurrent test of the same flow having `persisted` loaded is expected (see above),
780        // but then cargo should have found the job's build up to date and we would not be
781        // here; reaching this means something rebuilt the example.
782        panic!(
783            "failed to rename {} to {}: {err}",
784            staging.display(),
785            persisted.display()
786        )
787    });
788    // If `persisted` already links the same inode (an up-to-date build linked again), POSIX
789    // `rename` succeeds without removing `staging`.
790    match fs::remove_file(&staging) {
791        Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
792        result => result.unwrap(),
793    }
794    Ok(persisted)
795}
796
797/// Generates the inlined `__staged.rs` source for the source crate and writes it into the
798/// trybuild project, caching the (expensive) generation across test processes.
799///
800/// The staged source is a pure function of the source crate's files, and cargo rebuilds the
801/// test executable whenever those change, so the identity (path + mtime) of
802/// [`std::env::current_exe`] is a sound freshness proxy. All tests in a run share the same
803/// executable, so only the first test per test binary pays the ~1s `syn` parse +
804/// `prettyplease` unparse; the rest hit the cache. The stamp holds a single entry — the last
805/// executable to write `__staged.rs` — so a different test binary of the same crate
806/// regenerates on its first test (a no-op rewrite when sources are unchanged). Keeping old
807/// entries around would risk a stale match (e.g. an executable restored with an old mtime
808/// after another binary regenerated `__staged.rs` from different sources).
809pub(crate) fn write_staged_source_cached(source_dir: &Path, crate_name: &str, project_dir: &Path) {
810    let _span = tracing::debug_span!(target: "hydro_build", "gen_staged").entered();
811
812    let staged_path = path!(project_dir / "src" / "__staged.rs");
813    let stamp_path = path!(project_dir / ".hydro-staged-stamp");
814
815    let exe_stamp = std::env::current_exe().ok().and_then(|exe| {
816        let mtime = fs::metadata(&exe)
817            .ok()?
818            .modified()
819            .ok()?
820            .duration_since(std::time::SystemTime::UNIX_EPOCH)
821            .ok()?
822            .as_nanos();
823        Some(format!("{}\t{}", exe.display(), mtime))
824    });
825
826    let _concurrent_test_lock = CONCURRENT_TEST_LOCK.lock().unwrap();
827
828    fs::create_dir_all(path!(project_dir / "src")).unwrap();
829
830    // Hold an exclusive lock on the stamp file for the entire check + generate: when many
831    // test processes start concurrently with a cold cache, the first one generates while the
832    // others block here and then hit the cache, instead of all doing the expensive work.
833    let mut stamp_file = File::options()
834        .read(true)
835        .write(true)
836        .create(true)
837        .truncate(false)
838        .open(&stamp_path)
839        .unwrap();
840    stamp_file.lock().unwrap();
841
842    let mut existing_stamp = String::new();
843    if stamp_file.read_to_string(&mut existing_stamp).is_err() {
844        existing_stamp.clear();
845    }
846
847    if let Some(stamp) = &exe_stamp
848        && existing_stamp == *stamp
849        && staged_path.exists()
850    {
851        return;
852    }
853
854    let raw_toml_manifest = toml::from_str::<toml::Value>(
855        &fs::read_to_string(path!(source_dir / "Cargo.toml")).unwrap(),
856    )
857    .unwrap();
858
859    let maybe_custom_lib_path = raw_toml_manifest
860        .get("lib")
861        .and_then(|lib| lib.get("path"))
862        .and_then(|path| path.as_str());
863
864    let mut gen_staged = stageleft_tool::gen_staged_trybuild(
865        &maybe_custom_lib_path
866            .map(|s| path!(source_dir / s))
867            .unwrap_or_else(|| path!(source_dir / "src" / "lib.rs")),
868        &path!(source_dir / "Cargo.toml"),
869        crate_name,
870        Some("hydro___test".to_owned()),
871    );
872
873    gen_staged.attrs.insert(
874        0,
875        syn::parse_quote! {
876            #![allow(
877                unused,
878                ambiguous_glob_reexports,
879                clippy::suspicious_else_formatting,
880                unexpected_cfgs,
881                reason = "generated code"
882            )]
883        },
884    );
885
886    let inlined_staged = prettyplease::unparse(&gen_staged);
887
888    write_atomic(inlined_staged.as_bytes(), &staged_path).unwrap();
889
890    if let Some(stamp) = exe_stamp {
891        stamp_file.set_len(0).unwrap();
892        stamp_file.seek(SeekFrom::Start(0)).unwrap();
893        stamp_file.write_all(stamp.as_bytes()).unwrap();
894    }
895}
896
897pub fn create_trybuild()
898-> Result<(PathBuf, PathBuf, String, Option<Vec<String>>), trybuild_internals_api::error::Error> {
899    let _span = tracing::debug_span!(target: "hydro_build", "create_trybuild").entered();
900    let Metadata {
901        target_directory: target_dir,
902        workspace_root: workspace,
903        packages,
904    } = {
905        let _span = tracing::debug_span!(target: "hydro_build", "cargo_metadata").entered();
906        cargo::metadata()?
907    };
908
909    let source_dir = cargo::manifest_dir()?;
910    let mut source_manifest = dependencies::get_manifest(&source_dir)?;
911
912    let mut dev_dependency_features = vec![];
913    source_manifest.dev_dependencies.retain(|k, v| {
914        if source_manifest.dependencies.contains_key(k) {
915            // already a non-dev dependency, so drop the dep and put the features under the test flag
916            for feat in &v.features {
917                dev_dependency_features.push(format!("{}/{}", k, feat));
918            }
919
920            false
921        } else {
922            // only enable this in test mode, so make it optional otherwise
923            dev_dependency_features.push(format!("dep:{k}"));
924
925            v.optional = true;
926            true
927        }
928    });
929
930    // When the example is re-executed from a test binary by `example_test` (signaled via this
931    // env var), skip feature discovery: it would pick up the *test* binary's features (e.g.
932    // test-only harness features). A real `cargo run --example` invocation has no fingerprint
933    // hash in `argv[0]`, so discovery finds nothing there; emulating that here ensures the test
934    // exercises the example the same way it actually runs.
935    let mut features = if std::env::var("RUNNING_AS_EXAMPLE_TEST").is_ok_and(|v| v == "1") {
936        None
937    } else {
938        features::find()
939    };
940
941    let path_dependencies = source_manifest
942        .dependencies
943        .iter()
944        .filter_map(|(name, dep)| {
945            let path = dep.path.as_ref()?;
946            if packages.iter().any(|p| &p.name == name) {
947                // Skip path dependencies coming from the workspace itself
948                None
949            } else {
950                Some(PathDependency {
951                    name: name.clone(),
952                    normalized_path: path.canonicalize().ok()?,
953                    normalization: Normalization::PathDependencies,
954                })
955            }
956        })
957        .collect();
958
959    let crate_name = source_manifest.package.name.clone();
960    let project_dir = path!(target_dir / "hydro_trybuild" / crate_name /);
961    fs::create_dir_all(&project_dir)?;
962
963    let project_name = format!("{}-hydro-trybuild", crate_name);
964    let dylib_package_name = format!("{project_name}-dylib");
965    let mut manifest = Runner::make_manifest(
966        &workspace,
967        &project_name,
968        &source_dir,
969        &packages,
970        &[],
971        source_manifest,
972    )?;
973
974    if let Some(enabled_features) = &mut features {
975        enabled_features
976            .retain(|feature| manifest.features.contains_key(feature) || feature == "default");
977    }
978
979    for runtime_feature in HYDRO_RUNTIME_FEATURES {
980        manifest.features.insert(
981            format!("hydro___feature_{runtime_feature}"),
982            vec![format!("hydro_lang/{runtime_feature}")],
983        );
984    }
985
986    manifest
987        .dependencies
988        .get_mut("hydro_lang")
989        .unwrap()
990        .features
991        .push("runtime_support".to_owned());
992
993    manifest
994        .features
995        .insert("hydro___test".to_owned(), dev_dependency_features);
996
997    if manifest
998        .workspace
999        .as_ref()
1000        .is_some_and(|w| w.dependencies.is_empty())
1001    {
1002        manifest.workspace = None;
1003    }
1004
1005    let project = Project {
1006        dir: project_dir,
1007        source_dir,
1008        target_dir,
1009        name: project_name.clone(),
1010        update: Update::env()?,
1011        has_pass: false,
1012        has_compile_fail: false,
1013        features,
1014        workspace,
1015        path_dependencies,
1016        manifest,
1017        keep_going: false,
1018    };
1019
1020    {
1021        let _span = tracing::debug_span!(target: "hydro_build", "write_project_files").entered();
1022        let _concurrent_test_lock = CONCURRENT_TEST_LOCK.lock().unwrap();
1023
1024        let _project_lock = hydro_concurrent_cargo::lock_project(project.dir.as_ref());
1025
1026        fs::create_dir_all(path!(project.dir / "src"))?;
1027        fs::create_dir_all(path!(project.dir / "examples"))?;
1028
1029        let crate_name_ident = syn::Ident::new(
1030            &crate_name.replace('-', "_"),
1031            proc_macro2::Span::call_site(),
1032        );
1033
1034        write_atomic(
1035            prettyplease::unparse(&syn::parse_quote! {
1036                #![allow(unused_imports, unused_crate_dependencies, missing_docs, non_snake_case, unexpected_cfgs, unfulfilled_lint_expectations)]
1037
1038                pub mod __root {
1039                    pub use #crate_name_ident::*;
1040                    #[cfg(feature = "hydro___test")]
1041                    pub use super::__staged;
1042                }
1043
1044                #[cfg(feature = "hydro___test")]
1045                pub mod __staged;
1046            })
1047            .as_bytes(),
1048            &path!(project.dir / "src" / "lib.rs"),
1049        )
1050        .unwrap();
1051
1052        let base_manifest = toml::to_string(&project.manifest)?;
1053
1054        // Collect feature names for forwarding to dylib and dylib-examples crates
1055        let feature_names: Vec<_> = project.manifest.features.keys().cloned().collect();
1056
1057        // Create dylib crate directory
1058        let dylib_dir = path!(project.dir / "dylib");
1059        fs::create_dir_all(path!(dylib_dir / "src"))?;
1060
1061        let trybuild_crate_name_ident = syn::Ident::new(
1062            &project_name.replace('-', "_"),
1063            proc_macro2::Span::call_site(),
1064        );
1065        write_atomic(
1066            // The leading comment busts cargo's fingerprint for caches where the dylib was
1067            // built as a *primary* target (statically linking libstd); it must be built as a
1068            // dependency (with `-C prefer-dynamic`) for examples to link against it. The
1069            // linkage variant is not part of cargo's fingerprint, so a content change is
1070            // needed to force old caches to rebuild.
1071            [
1072                "// v2: dylib must be built as a dependency (prefer-dynamic).\n".as_bytes(),
1073                prettyplease::unparse(&syn::parse_quote! {
1074                    #![allow(unused_imports, unused_crate_dependencies, missing_docs, non_snake_case, unexpected_cfgs, unfulfilled_lint_expectations)]
1075                    pub use #trybuild_crate_name_ident::*;
1076                })
1077                .as_bytes(),
1078            ]
1079            .concat()
1080            .as_slice(),
1081            &path!(dylib_dir / "src" / "lib.rs"),
1082        )?;
1083
1084        let serialized_edition = toml::to_string(
1085            &vec![("edition", &project.manifest.package.edition)]
1086                .into_iter()
1087                .collect::<std::collections::HashMap<_, _>>(),
1088        )
1089        .unwrap();
1090
1091        // Dylib crate Cargo.toml - only dylib crate-type, with feature forwarding to base crate
1092        // On Windows, we currently disable dylib compilation due to https://github.com/bevyengine/bevy/pull/2016
1093        let dylib_features_section = feature_names
1094            .iter()
1095            .map(|f| format!("{f} = [\"{project_name}/{f}\"]"))
1096            .collect::<Vec<_>>()
1097            .join("\n");
1098
1099        // The dylib is the one shared artifact cargo does not name per configuration (unless
1100        // `__CARGO_DEFAULT_LIB_METADATA` is set), so `hydro_concurrent_cargo` decides its
1101        // `[lib] name` and only changes it under the exclusive prebuild lock, once every
1102        // in-flight final build that links the current name has finished. Reuse whatever name
1103        // the manifest has now; a fresh project gets this configuration's name. The package
1104        // name (and so `Cargo.lock`) never changes, and generated code never names the target
1105        // — it reaches the dylib through the `dylib-examples` dependency rename below.
1106        let dylib_lib_name = hydro_concurrent_cargo::current_dylib_lib_name(project.dir.as_ref())
1107            .unwrap_or_else(|| {
1108                hydro_concurrent_cargo::dylib_lib_name(&dylib_package_name, ENCODED_RUSTFLAGS)
1109            });
1110
1111        let dylib_manifest = format!(
1112            r#"[package]
1113name = "{dylib_package_name}"
1114version = "0.0.0"
1115{}
1116
1117[lib]
1118name = "{dylib_lib_name}"
1119crate-type = ["{}"]
1120
1121[dependencies]
1122{project_name} = {{ path = "..", default-features = false }}
1123
1124[features]
1125{dylib_features_section}
1126"#,
1127            serialized_edition,
1128            if cfg!(target_os = "windows") {
1129                "rlib"
1130            } else {
1131                "dylib"
1132            }
1133        );
1134        write_atomic(dylib_manifest.as_ref(), &path!(dylib_dir / "Cargo.toml"))?;
1135
1136        let dylib_examples_dir = path!(project.dir / "dylib-examples");
1137        fs::create_dir_all(path!(dylib_examples_dir / "src"))?;
1138        fs::create_dir_all(path!(dylib_examples_dir / "examples"))?;
1139
1140        write_atomic(
1141            b"#![allow(unused_crate_dependencies)]\n",
1142            &path!(dylib_examples_dir / "src" / "lib.rs"),
1143        )?;
1144
1145        // Build feature forwarding for dylib-examples - forward through the (renamed) dylib crate
1146        let features_section = feature_names
1147            .iter()
1148            .map(|f| format!("{f} = [\"{project_name}/{f}\"]"))
1149            .collect::<Vec<_>>()
1150            .join("\n");
1151
1152        // Dylib-examples crate Cargo.toml - depends *only* on the dylib crate, renamed to the
1153        // base crate's package name so that generated examples referencing
1154        // `{crate}_hydro_trybuild` resolve to the dylib. This is what makes dynamic linking
1155        // actually kick in: if the base crate were also a direct dependency, rustc would
1156        // statically link its rlib (and the entire dependency graph) into every example,
1157        // making the per-example "final compile" link take several seconds. With only the
1158        // dylib in scope, examples link against the prebuilt shared library instead.
1159        //
1160        // The dylib is a regular dependency (not a dev-dependency) so that prebuilding this
1161        // crate's (empty) lib builds the dylib as a dependency, which is required for cargo
1162        // to pass `-C prefer-dynamic` (see the prebuild in `compile_trybuild_example`).
1163        let dylib_examples_manifest = format!(
1164            r#"[package]
1165name = "{project_name}-dylib-examples"
1166version = "0.0.0"
1167{}
1168
1169[dependencies]
1170{project_name} = {{ package = "{project_name}-dylib", path = "../dylib", default-features = false }}
1171
1172[features]
1173{features_section}
1174
1175[[example]]
1176name = "sim-dylib"
1177crate-type = ["cdylib"]
1178"#,
1179            serialized_edition
1180        );
1181        write_atomic(
1182            dylib_examples_manifest.as_ref(),
1183            &path!(dylib_examples_dir / "Cargo.toml"),
1184        )?;
1185
1186        // The simulator's `sim-dylib` example wrapper in the dylib-examples crate.
1187        let sim_dylib_contents = prettyplease::unparse(&syn::parse_quote! {
1188            #![allow(unused_imports, unused_crate_dependencies, missing_docs, non_snake_case, unexpected_cfgs, unfulfilled_lint_expectations)]
1189            include!(std::concat!(env!("TRYBUILD_LIB_NAME"), ".rs"));
1190        });
1191        write_atomic(
1192            sim_dylib_contents.as_bytes(),
1193            &path!(dylib_examples_dir / "examples" / "sim-dylib.rs"),
1194        )?;
1195        let _ = fs::remove_file(path!(project.dir / "examples" / "sim-dylib.rs"));
1196
1197        let workspace_manifest = format!(
1198            r#"{}
1199[workspace]
1200members = ["dylib", "dylib-examples"]
1201"#,
1202            base_manifest,
1203        );
1204
1205        write_atomic(
1206            workspace_manifest.as_ref(),
1207            &path!(project.dir / "Cargo.toml"),
1208        )?;
1209
1210        // Compute hash for cache invalidation, covering all generated manifests (the dylib and
1211        // dylib-examples manifests affect Cargo.lock, so they must participate in the hash).
1212        // The dylib's target name does not affect Cargo.lock (only package names do), so it is
1213        // excluded: otherwise every toolchain/rustflags switch would pay for a lockfile
1214        // regeneration.
1215        let manifest_hash = {
1216            let mut hasher = Sha256::new();
1217            hasher.update(&workspace_manifest);
1218            hasher.update(dylib_manifest.replace(&dylib_lib_name, ""));
1219            hasher.update(&dylib_examples_manifest);
1220            format!("{:X}", hasher.finalize())
1221                .chars()
1222                .take(8)
1223                .collect::<String>()
1224        };
1225
1226        let workspace_cargo_lock = path!(project.workspace / "Cargo.lock");
1227        let workspace_cargo_lock_contents_and_hash = if workspace_cargo_lock.exists() {
1228            let cargo_lock_contents = fs::read_to_string(&workspace_cargo_lock)?;
1229
1230            let hash = format!("{:X}", Sha256::digest(&cargo_lock_contents))
1231                .chars()
1232                .take(8)
1233                .collect::<String>();
1234
1235            Some((cargo_lock_contents, hash))
1236        } else {
1237            None
1238        };
1239
1240        let trybuild_hash = format!(
1241            "{}-{}",
1242            manifest_hash,
1243            workspace_cargo_lock_contents_and_hash
1244                .as_ref()
1245                .map(|(_contents, hash)| &**hash)
1246                .unwrap_or_default()
1247        );
1248
1249        if !check_contents(
1250            trybuild_hash.as_bytes(),
1251            &path!(project.dir / ".hydro-trybuild-manifest"),
1252        )
1253        .is_ok_and(|b| b)
1254        {
1255            let _span = tracing::debug_span!(target: "hydro_build", "update_lockfile").entered();
1256            // this is expensive, so we only do it if the manifest changed
1257            if let Some((cargo_lock_contents, _)) = workspace_cargo_lock_contents_and_hash {
1258                // only overwrite when the hash changed, because writing Cargo.lock must be
1259                // immediately followed by a local `cargo update -w`
1260                write_atomic(
1261                    cargo_lock_contents.as_ref(),
1262                    &path!(project.dir / "Cargo.lock"),
1263                )?;
1264            } else {
1265                let _ = cargo::cargo(&project).arg("generate-lockfile").status();
1266            }
1267
1268            // not `--offline` because some new runtime features may be enabled
1269            std::process::Command::new("cargo")
1270                .current_dir(&project.dir)
1271                .args(["update", "-w"]) // -w to not actually update any versions
1272                .stdout(std::process::Stdio::null())
1273                .stderr(std::process::Stdio::null())
1274                .status()
1275                .unwrap();
1276
1277            write_atomic(
1278                trybuild_hash.as_bytes(),
1279                &path!(project.dir / ".hydro-trybuild-manifest"),
1280            )?;
1281        }
1282
1283        // Create examples folder for base crate (static linking)
1284        let examples_folder = path!(project.dir / "examples");
1285        fs::create_dir_all(&examples_folder)?;
1286
1287        let workspace_dot_cargo_config_toml = path!(project.workspace / ".cargo" / "config.toml");
1288        if workspace_dot_cargo_config_toml.exists() {
1289            let dot_cargo_folder = path!(project.dir / ".cargo");
1290            fs::create_dir_all(&dot_cargo_folder)?;
1291
1292            write_atomic(
1293                fs::read_to_string(&workspace_dot_cargo_config_toml)?.as_ref(),
1294                &path!(dot_cargo_folder / "config.toml"),
1295            )?;
1296        }
1297
1298        let vscode_folder = path!(project.dir / ".vscode");
1299        fs::create_dir_all(&vscode_folder)?;
1300        write_atomic(
1301            include_bytes!("./vscode-trybuild.json"),
1302            &path!(vscode_folder / "settings.json"),
1303        )?;
1304    }
1305
1306    Ok((
1307        project.dir.as_ref().into(),
1308        project.target_dir.as_ref().into(),
1309        dylib_package_name,
1310        project.features,
1311    ))
1312}
1313
1314fn check_contents(contents: &[u8], path: &Path) -> Result<bool, std::io::Error> {
1315    let mut file = File::options()
1316        .read(true)
1317        .write(false)
1318        .create(false)
1319        .truncate(false)
1320        .open(path)?;
1321    file.lock()?;
1322
1323    let mut existing_contents = Vec::new();
1324    file.read_to_end(&mut existing_contents)?;
1325    Ok(existing_contents == contents)
1326}
1327
1328pub(crate) fn write_atomic(contents: &[u8], path: &Path) -> Result<(), std::io::Error> {
1329    let mut file = File::options()
1330        .read(true)
1331        .write(true)
1332        .create(true)
1333        .truncate(false)
1334        .open(path)?;
1335
1336    let mut existing_contents = Vec::new();
1337    file.read_to_end(&mut existing_contents)?;
1338    if existing_contents != contents {
1339        file.lock()?;
1340        file.seek(SeekFrom::Start(0))?;
1341        file.set_len(0)?;
1342        file.write_all(contents)?;
1343    }
1344
1345    Ok(())
1346}