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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
32pub enum LinkingMode {
33 #[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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
50pub enum DeployMode {
51 #[cfg(feature = "deploy")]
52 HydroDeploy,
54 #[cfg(any(feature = "docker_deploy", feature = "ecs_deploy"))]
55 Containerized,
57 #[cfg(feature = "maelstrom")]
58 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
67pub 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 pub dylib_package_name: String,
99 pub features: Option<Vec<String>>,
100 #[cfg(any(feature = "deploy", feature = "maelstrom"))]
101 #[cfg_attr(
104 not(feature = "deploy"),
105 expect(dead_code, reason = "only read by the deploy backends")
106 )]
107 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 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 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 "e! { __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 ); )*
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 #(
289 let _ = #root::runtime_support::tokio::spawn( #sidecars ); )*
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 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 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(); #(
337 let _ = #root::runtime_support::tokio::spawn( #sidecars ); )*
339
340 let _ = #dfir_ident.run().await;
341 }
342 }
343 }
344 };
345 source_ast
346}
347
348#[cfg(any(feature = "sim", feature = "maelstrom"))]
351pub struct ExampleBuildConfig<'a> {
352 pub trybuild: TrybuildConfig,
354 pub bin_name: String,
358 pub runtime_feature: &'a str,
361 pub example_name: String,
364 pub crate_type: Option<&'a str>,
367 pub set_trybuild_lib_name: bool,
370}
371
372#[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
389const ENCODED_RUSTFLAGS: &str = env!("HYDRO_ENCODED_RUSTFLAGS");
393
394#[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#[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#[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 let crate_to_compile = path!(trybuild.project_dir / "dylib-examples");
474
475 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 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 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 drop(prebuild_span);
548 (per_job, guard, cargo_lock)
549 };
550
551 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 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 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 command.arg(format!("-Cmetadata={bin_name}"));
613
614 if cfg!(any(target_os = "linux", target_os = "macos")) {
615 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 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 "-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 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 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 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 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 if same_file::is_same_file(&out, &persisted).unwrap_or(false) {
756 return Ok(persisted);
757 }
758
759 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 fs::copy(&out, &staging).unwrap();
776 }
777 fs::rename(&staging, &persisted).unwrap_or_else(|err| {
778 panic!(
783 "failed to rename {} to {}: {err}",
784 staging.display(),
785 persisted.display()
786 )
787 });
788 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
797pub(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 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 for feat in &v.features {
917 dev_dependency_features.push(format!("{}/{}", k, feat));
918 }
919
920 false
921 } else {
922 dev_dependency_features.push(format!("dep:{k}"));
924
925 v.optional = true;
926 true
927 }
928 });
929
930 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 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 let feature_names: Vec<_> = project.manifest.features.keys().cloned().collect();
1056
1057 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 [
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 let dylib_features_section = feature_names
1094 .iter()
1095 .map(|f| format!("{f} = [\"{project_name}/{f}\"]"))
1096 .collect::<Vec<_>>()
1097 .join("\n");
1098
1099 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 let features_section = feature_names
1147 .iter()
1148 .map(|f| format!("{f} = [\"{project_name}/{f}\"]"))
1149 .collect::<Vec<_>>()
1150 .join("\n");
1151
1152 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 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 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 if let Some((cargo_lock_contents, _)) = workspace_cargo_lock_contents_and_hash {
1258 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 std::process::Command::new("cargo")
1270 .current_dir(&project.dir)
1271 .args(["update", "-w"]) .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 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}