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::DfirGraph;
9use sha2::{Digest, Sha256};
10#[cfg(any(feature = "deploy", feature = "maelstrom"))]
11use stageleft::internal::quote;
12#[cfg(any(feature = "deploy", feature = "maelstrom"))]
13use syn::visit_mut::VisitMut;
14use trybuild_internals_api::cargo::{self, Metadata};
15use trybuild_internals_api::env::Update;
16use trybuild_internals_api::run::{PathDependency, Project};
17use trybuild_internals_api::{Runner, dependencies, features, path};
18
19#[cfg(any(feature = "deploy", feature = "maelstrom"))]
20use super::rewriters::UseTestModeStaged;
21
22pub const HYDRO_RUNTIME_FEATURES: &[&str] = &[
23 "deploy_integration",
24 "runtime_measure",
25 "docker_runtime",
26 "ecs_runtime",
27 "maelstrom_runtime",
28];
29
30#[cfg(any(feature = "deploy", feature = "maelstrom"))]
31#[derive(Debug, Clone, Copy, PartialEq, Eq)]
35pub enum LinkingMode {
36 Static,
37 #[cfg(feature = "deploy")]
38 Dynamic,
39}
40
41#[cfg(any(feature = "deploy", feature = "maelstrom"))]
42#[derive(Debug, Clone, Copy, PartialEq, Eq)]
44pub enum DeployMode {
45 #[cfg(feature = "deploy")]
46 HydroDeploy,
48 #[cfg(any(feature = "docker_deploy", feature = "ecs_deploy"))]
49 Containerized,
51 #[cfg(feature = "maelstrom")]
52 Maelstrom,
54}
55
56pub(crate) static IS_TEST: std::sync::atomic::AtomicBool =
57 std::sync::atomic::AtomicBool::new(false);
58
59pub(crate) static CONCURRENT_TEST_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
60
61pub fn init_test() {
75 IS_TEST.store(true, std::sync::atomic::Ordering::Relaxed);
76}
77
78#[cfg(any(feature = "deploy", feature = "maelstrom"))]
79fn clean_bin_name_prefix(bin_name_prefix: &str) -> String {
80 bin_name_prefix
81 .replace("::", "__")
82 .replace(" ", "_")
83 .replace(",", "_")
84 .replace("<", "_")
85 .replace(">", "")
86 .replace("(", "")
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 features: Option<Vec<String>>,
97 #[cfg(feature = "deploy")]
98 pub linking_mode: LinkingMode,
102}
103
104#[cfg(any(feature = "deploy", feature = "maelstrom"))]
105pub fn create_graph_trybuild(
106 graph: DfirGraph,
107 extra_stmts: &[syn::Stmt],
108 sidecars: &[syn::Expr],
109 bin_name_prefix: Option<&str>,
110 deploy_mode: DeployMode,
111 linking_mode: LinkingMode,
112) -> (String, TrybuildConfig) {
113 let source_dir = cargo::manifest_dir().unwrap();
114 let source_manifest = dependencies::get_manifest(&source_dir).unwrap();
115 let crate_name = source_manifest.package.name.replace("-", "_");
116
117 let is_test = IS_TEST.load(std::sync::atomic::Ordering::Relaxed);
118
119 let generated_code = compile_graph_trybuild(
120 graph,
121 extra_stmts,
122 sidecars,
123 &crate_name,
124 is_test,
125 deploy_mode,
126 );
127
128 let inlined_staged = if is_test {
129 let raw_toml_manifest = toml::from_str::<toml::Value>(
130 &fs::read_to_string(path!(source_dir / "Cargo.toml")).unwrap(),
131 )
132 .unwrap();
133
134 let maybe_custom_lib_path = raw_toml_manifest
135 .get("lib")
136 .and_then(|lib| lib.get("path"))
137 .and_then(|path| path.as_str());
138
139 let mut gen_staged = stageleft_tool::gen_staged_trybuild(
140 &maybe_custom_lib_path
141 .map(|s| path!(source_dir / s))
142 .unwrap_or_else(|| path!(source_dir / "src" / "lib.rs")),
143 &path!(source_dir / "Cargo.toml"),
144 &crate_name,
145 Some("hydro___test".to_owned()),
146 );
147
148 gen_staged.attrs.insert(
149 0,
150 syn::parse_quote! {
151 #![allow(
152 unused,
153 ambiguous_glob_reexports,
154 clippy::suspicious_else_formatting,
155 unexpected_cfgs,
156 reason = "generated code"
157 )]
158 },
159 );
160
161 Some(prettyplease::unparse(&gen_staged))
162 } else {
163 None
164 };
165
166 let source = prettyplease::unparse(&generated_code);
167
168 let hash = format!("{:X}", Sha256::digest(&source))
169 .chars()
170 .take(8)
171 .collect::<String>();
172
173 let bin_name = if let Some(bin_name_prefix) = &bin_name_prefix {
174 format!("{}_{}", clean_bin_name_prefix(bin_name_prefix), &hash)
175 } else {
176 hash
177 };
178
179 let (project_dir, target_dir, mut cur_bin_enabled_features) = create_trybuild().unwrap();
180
181 let examples_dir = match linking_mode {
183 LinkingMode::Static => path!(project_dir / "examples"),
184 #[cfg(feature = "deploy")]
185 LinkingMode::Dynamic => path!(project_dir / "dylib-examples" / "examples"),
186 };
187
188 fs::create_dir_all(&examples_dir).unwrap();
190
191 let out_path = path!(examples_dir / format!("{bin_name}.rs"));
192 {
193 let _concurrent_test_lock = CONCURRENT_TEST_LOCK.lock().unwrap();
194 write_atomic(source.as_ref(), &out_path).unwrap();
195 }
196
197 if let Some(inlined_staged) = inlined_staged {
198 let staged_path = path!(project_dir / "src" / "__staged.rs");
199 {
200 let _concurrent_test_lock = CONCURRENT_TEST_LOCK.lock().unwrap();
201 write_atomic(inlined_staged.as_bytes(), &staged_path).unwrap();
202 }
203 }
204
205 if is_test {
206 if cur_bin_enabled_features.is_none() {
207 cur_bin_enabled_features = Some(vec![]);
208 }
209
210 cur_bin_enabled_features
211 .as_mut()
212 .unwrap()
213 .push("hydro___test".to_owned());
214 }
215
216 (
217 bin_name,
218 TrybuildConfig {
219 project_dir,
220 target_dir,
221 features: cur_bin_enabled_features,
222 #[cfg(feature = "deploy")]
223 linking_mode,
224 },
225 )
226}
227
228#[cfg(any(feature = "deploy", feature = "maelstrom"))]
229pub fn compile_graph_trybuild(
230 partitioned_graph: DfirGraph,
231 extra_stmts: &[syn::Stmt],
232 sidecars: &[syn::Expr],
233 crate_name: &str,
234 is_test: bool,
235 deploy_mode: DeployMode,
236) -> syn::File {
237 use crate::staging_util::get_this_crate;
238
239 let mut diagnostics = Diagnostics::new();
240 let mut dfir_expr: syn::Expr = syn::parse2(
241 partitioned_graph
242 .as_code("e! { __root_dfir_rs }, true, quote!(), &mut diagnostics)
243 .expect("DFIR code generation failed with diagnostics."),
244 )
245 .unwrap();
246
247 if is_test {
248 UseTestModeStaged { crate_name }.visit_expr_mut(&mut dfir_expr);
249 }
250
251 let orig_crate_name = quote::format_ident!("{}", crate_name);
252 let trybuild_crate_name_ident = quote::format_ident!("{}_hydro_trybuild", crate_name);
253 let root = get_this_crate();
254 let tokio_main_ident = format!("{}::runtime_support::tokio", root);
255 let dfir_ident = quote::format_ident!("{}", crate::compile::DFIR_IDENT);
256
257 let source_ast: syn::File = match deploy_mode {
258 #[cfg(any(feature = "docker_deploy", feature = "ecs_deploy"))]
259 DeployMode::Containerized => {
260 syn::parse_quote! {
261 #![allow(unused_imports, unused_crate_dependencies, missing_docs, non_snake_case)]
262 use #trybuild_crate_name_ident::__root as #orig_crate_name;
263 use #trybuild_crate_name_ident::__staged::__deps::*;
264 use #root::prelude::*;
265 use #root::runtime_support::dfir_rs as __root_dfir_rs;
266 pub use #trybuild_crate_name_ident::__staged;
267
268 #[allow(unused)]
269 async fn __hydro_runtime<'a>() -> #root::runtime_support::dfir_rs::scheduled::graph::Dfir<'a> {
270 #( #extra_stmts )*
272
273 #dfir_expr
275 }
276
277 #[#root::runtime_support::tokio::main(crate = #tokio_main_ident, flavor = "current_thread")]
278 async fn main() {
279 #root::telemetry::initialize_tracing();
280
281 let mut #dfir_ident = __hydro_runtime().await;
282
283 let local_set = #root::runtime_support::tokio::task::LocalSet::new();
284 #(
285 let _ = local_set.spawn_local( #sidecars ); )*
287
288 let _ = local_set.run_until(#dfir_ident.run()).await;
289 }
290 }
291 }
292 #[cfg(feature = "deploy")]
293 DeployMode::HydroDeploy => {
294 syn::parse_quote! {
295 #![allow(unused_imports, unused_crate_dependencies, missing_docs, non_snake_case)]
296 use #trybuild_crate_name_ident::__root as #orig_crate_name;
297 use #trybuild_crate_name_ident::__staged::__deps::*;
298 use #root::prelude::*;
299 use #root::runtime_support::dfir_rs as __root_dfir_rs;
300 pub use #trybuild_crate_name_ident::__staged;
301
302 #[allow(unused)]
303 fn __hydro_runtime<'a>(
304 __hydro_lang_trybuild_cli: &'a #root::runtime_support::hydro_deploy_integration::DeployPorts<#root::__staged::deploy::deploy_runtime::HydroMeta>
305 )
306 -> #root::runtime_support::dfir_rs::scheduled::graph::Dfir<'a>
307 {
308 #( #extra_stmts )*
309
310 #dfir_expr
311 }
312
313 #[#root::runtime_support::tokio::main(crate = #tokio_main_ident, flavor = "current_thread")]
314 async fn main() {
315 let ports = #root::runtime_support::launch::init_no_ack_start().await;
316 let #dfir_ident = __hydro_runtime(&ports);
317 println!("ack start");
318
319 let local_set = #root::runtime_support::tokio::task::LocalSet::new();
323 #(
324 let _ = local_set.spawn_local( #sidecars ); )*
326
327 let _ = local_set.run_until(#root::runtime_support::launch::run_stdin_commands(#dfir_ident)).await;
328 }
329 }
330 }
331 #[cfg(feature = "maelstrom")]
332 DeployMode::Maelstrom => {
333 syn::parse_quote! {
334 #![allow(unused_imports, unused_crate_dependencies, missing_docs, non_snake_case)]
335 use #trybuild_crate_name_ident::__root as #orig_crate_name;
336 use #trybuild_crate_name_ident::__staged::__deps::*;
337 use #root::prelude::*;
338 use #root::runtime_support::dfir_rs as __root_dfir_rs;
339 pub use #trybuild_crate_name_ident::__staged;
340
341 #[allow(unused)]
342 fn __hydro_runtime<'a>(
343 __hydro_lang_maelstrom_meta: &'a #root::__staged::deploy::maelstrom::deploy_runtime_maelstrom::MaelstromMeta
344 )
345 -> #root::runtime_support::dfir_rs::scheduled::graph::Dfir<'a>
346 {
347 #( #extra_stmts )*
348
349 #dfir_expr
350 }
351
352 #[#root::runtime_support::tokio::main(crate = #tokio_main_ident, flavor = "current_thread")]
353 async fn main() {
354 #root::telemetry::initialize_tracing();
355
356 let __hydro_lang_maelstrom_meta = #root::__staged::deploy::maelstrom::deploy_runtime_maelstrom::maelstrom_init();
358
359 let mut #dfir_ident = __hydro_runtime(&__hydro_lang_maelstrom_meta);
360
361 __hydro_lang_maelstrom_meta.start_receiving(); let local_set = #root::runtime_support::tokio::task::LocalSet::new();
364 #(
365 let _ = local_set.spawn_local( #sidecars ); )*
367
368 let _ = local_set.run_until(#dfir_ident.run()).await;
369 }
370 }
371 }
372 };
373 source_ast
374}
375
376pub fn create_trybuild()
377-> Result<(PathBuf, PathBuf, Option<Vec<String>>), trybuild_internals_api::error::Error> {
378 let Metadata {
379 target_directory: target_dir,
380 workspace_root: workspace,
381 packages,
382 } = cargo::metadata()?;
383
384 let source_dir = cargo::manifest_dir()?;
385 let mut source_manifest = dependencies::get_manifest(&source_dir)?;
386
387 let mut dev_dependency_features = vec![];
388 source_manifest.dev_dependencies.retain(|k, v| {
389 if source_manifest.dependencies.contains_key(k) {
390 for feat in &v.features {
392 dev_dependency_features.push(format!("{}/{}", k, feat));
393 }
394
395 false
396 } else {
397 dev_dependency_features.push(format!("dep:{k}"));
399
400 v.optional = true;
401 true
402 }
403 });
404
405 let mut features = features::find();
406
407 let path_dependencies = source_manifest
408 .dependencies
409 .iter()
410 .filter_map(|(name, dep)| {
411 let path = dep.path.as_ref()?;
412 if packages.iter().any(|p| &p.name == name) {
413 None
415 } else {
416 Some(PathDependency {
417 name: name.clone(),
418 normalized_path: path.canonicalize().ok()?,
419 })
420 }
421 })
422 .collect();
423
424 let crate_name = source_manifest.package.name.clone();
425 let project_dir = path!(target_dir / "hydro_trybuild" / crate_name /);
426 fs::create_dir_all(&project_dir)?;
427
428 let project_name = format!("{}-hydro-trybuild", crate_name);
429 let mut manifest = Runner::make_manifest(
430 &workspace,
431 &project_name,
432 &source_dir,
433 &packages,
434 &[],
435 source_manifest,
436 )?;
437
438 if let Some(enabled_features) = &mut features {
439 enabled_features
440 .retain(|feature| manifest.features.contains_key(feature) || feature == "default");
441 }
442
443 for runtime_feature in HYDRO_RUNTIME_FEATURES {
444 manifest.features.insert(
445 format!("hydro___feature_{runtime_feature}"),
446 vec![format!("hydro_lang/{runtime_feature}")],
447 );
448 }
449
450 manifest
451 .dependencies
452 .get_mut("hydro_lang")
453 .unwrap()
454 .features
455 .push("runtime_support".to_owned());
456
457 manifest
458 .features
459 .insert("hydro___test".to_owned(), dev_dependency_features);
460
461 if manifest
462 .workspace
463 .as_ref()
464 .is_some_and(|w| w.dependencies.is_empty())
465 {
466 manifest.workspace = None;
467 }
468
469 let project = Project {
470 dir: project_dir,
471 source_dir,
472 target_dir,
473 name: project_name.clone(),
474 update: Update::env()?,
475 has_pass: false,
476 has_compile_fail: false,
477 features,
478 workspace,
479 path_dependencies,
480 manifest,
481 keep_going: false,
482 };
483
484 {
485 let _concurrent_test_lock = CONCURRENT_TEST_LOCK.lock().unwrap();
486
487 let project_lock = File::create(path!(project.dir / ".hydro-trybuild-lock"))?;
488 project_lock.lock()?;
489
490 fs::create_dir_all(path!(project.dir / "src"))?;
491 fs::create_dir_all(path!(project.dir / "examples"))?;
492
493 let crate_name_ident = syn::Ident::new(
494 &crate_name.replace("-", "_"),
495 proc_macro2::Span::call_site(),
496 );
497
498 write_atomic(
499 prettyplease::unparse(&syn::parse_quote! {
500 #![allow(unused_imports, unused_crate_dependencies, missing_docs, non_snake_case)]
501
502 pub use #crate_name_ident as __root;
503
504 #[cfg(feature = "hydro___test")]
505 pub mod __staged;
506
507 #[cfg(not(feature = "hydro___test"))]
508 pub use #crate_name_ident::__staged;
509 })
510 .as_bytes(),
511 &path!(project.dir / "src" / "lib.rs"),
512 )
513 .unwrap();
514
515 let base_manifest = toml::to_string(&project.manifest)?;
516
517 let feature_names: Vec<_> = project.manifest.features.keys().cloned().collect();
519
520 let dylib_dir = path!(project.dir / "dylib");
522 fs::create_dir_all(path!(dylib_dir / "src"))?;
523
524 let trybuild_crate_name_ident = syn::Ident::new(
525 &project_name.replace("-", "_"),
526 proc_macro2::Span::call_site(),
527 );
528 write_atomic(
529 prettyplease::unparse(&syn::parse_quote! {
530 #![allow(unused_imports, unused_crate_dependencies, missing_docs, non_snake_case)]
531 pub use #trybuild_crate_name_ident::*;
532 })
533 .as_bytes(),
534 &path!(dylib_dir / "src" / "lib.rs"),
535 )?;
536
537 let serialized_edition = toml::to_string(
538 &vec![("edition", &project.manifest.package.edition)]
539 .into_iter()
540 .collect::<std::collections::HashMap<_, _>>(),
541 )
542 .unwrap();
543
544 let dylib_manifest = format!(
548 r#"[package]
549name = "{project_name}-dylib"
550version = "0.0.0"
551{}
552
553[lib]
554crate-type = ["{}"]
555
556[dependencies]
557{project_name} = {{ path = "..", default-features = false }}
558"#,
559 serialized_edition,
560 if cfg!(target_os = "windows") {
561 "rlib"
562 } else {
563 "dylib"
564 }
565 );
566 write_atomic(dylib_manifest.as_ref(), &path!(dylib_dir / "Cargo.toml"))?;
567
568 let dylib_examples_dir = path!(project.dir / "dylib-examples");
569 fs::create_dir_all(path!(dylib_examples_dir / "src"))?;
570 fs::create_dir_all(path!(dylib_examples_dir / "examples"))?;
571
572 write_atomic(
573 b"#![allow(unused_crate_dependencies)]\n",
574 &path!(dylib_examples_dir / "src" / "lib.rs"),
575 )?;
576
577 let features_section = feature_names
579 .iter()
580 .map(|f| format!("{f} = [\"{project_name}/{f}\"]"))
581 .collect::<Vec<_>>()
582 .join("\n");
583
584 let dylib_examples_manifest = format!(
586 r#"[package]
587name = "{project_name}-dylib-examples"
588version = "0.0.0"
589{}
590
591[dev-dependencies]
592{project_name} = {{ path = "..", default-features = false }}
593{project_name}-dylib = {{ path = "../dylib", default-features = false }}
594
595[features]
596{features_section}
597
598[[example]]
599name = "sim-dylib"
600crate-type = ["cdylib"]
601"#,
602 serialized_edition
603 );
604 write_atomic(
605 dylib_examples_manifest.as_ref(),
606 &path!(dylib_examples_dir / "Cargo.toml"),
607 )?;
608
609 let sim_dylib_contents = prettyplease::unparse(&syn::parse_quote! {
611 #![allow(unused_imports, unused_crate_dependencies, missing_docs, non_snake_case)]
612 include!(std::concat!(env!("TRYBUILD_LIB_NAME"), ".rs"));
613 });
614 write_atomic(
615 sim_dylib_contents.as_bytes(),
616 &path!(project.dir / "examples" / "sim-dylib.rs"),
617 )?;
618 write_atomic(
619 sim_dylib_contents.as_bytes(),
620 &path!(dylib_examples_dir / "examples" / "sim-dylib.rs"),
621 )?;
622
623 let workspace_manifest = format!(
624 r#"{}
625[[example]]
626name = "sim-dylib"
627crate-type = ["cdylib"]
628
629[workspace]
630members = ["dylib", "dylib-examples"]
631"#,
632 base_manifest,
633 );
634
635 write_atomic(
636 workspace_manifest.as_ref(),
637 &path!(project.dir / "Cargo.toml"),
638 )?;
639
640 let manifest_hash = format!("{:X}", Sha256::digest(&workspace_manifest))
642 .chars()
643 .take(8)
644 .collect::<String>();
645
646 let workspace_cargo_lock = path!(project.workspace / "Cargo.lock");
647 let workspace_cargo_lock_contents_and_hash = if workspace_cargo_lock.exists() {
648 let cargo_lock_contents = fs::read_to_string(&workspace_cargo_lock)?;
649
650 let hash = format!("{:X}", Sha256::digest(&cargo_lock_contents))
651 .chars()
652 .take(8)
653 .collect::<String>();
654
655 Some((cargo_lock_contents, hash))
656 } else {
657 None
658 };
659
660 let trybuild_hash = format!(
661 "{}-{}",
662 manifest_hash,
663 workspace_cargo_lock_contents_and_hash
664 .as_ref()
665 .map(|(_contents, hash)| &**hash)
666 .unwrap_or_default()
667 );
668
669 if !check_contents(
670 trybuild_hash.as_bytes(),
671 &path!(project.dir / ".hydro-trybuild-manifest"),
672 )
673 .is_ok_and(|b| b)
674 {
675 if let Some((cargo_lock_contents, _)) = workspace_cargo_lock_contents_and_hash {
677 write_atomic(
680 cargo_lock_contents.as_ref(),
681 &path!(project.dir / "Cargo.lock"),
682 )?;
683 } else {
684 let _ = cargo::cargo(&project).arg("generate-lockfile").status();
685 }
686
687 std::process::Command::new("cargo")
689 .current_dir(&project.dir)
690 .args(["update", "-w"]) .stdout(std::process::Stdio::null())
692 .stderr(std::process::Stdio::null())
693 .status()
694 .unwrap();
695
696 write_atomic(
697 trybuild_hash.as_bytes(),
698 &path!(project.dir / ".hydro-trybuild-manifest"),
699 )?;
700 }
701
702 let examples_folder = path!(project.dir / "examples");
704 fs::create_dir_all(&examples_folder)?;
705
706 let workspace_dot_cargo_config_toml = path!(project.workspace / ".cargo" / "config.toml");
707 if workspace_dot_cargo_config_toml.exists() {
708 let dot_cargo_folder = path!(project.dir / ".cargo");
709 fs::create_dir_all(&dot_cargo_folder)?;
710
711 write_atomic(
712 fs::read_to_string(&workspace_dot_cargo_config_toml)?.as_ref(),
713 &path!(dot_cargo_folder / "config.toml"),
714 )?;
715 }
716
717 let vscode_folder = path!(project.dir / ".vscode");
718 fs::create_dir_all(&vscode_folder)?;
719 write_atomic(
720 include_bytes!("./vscode-trybuild.json"),
721 &path!(vscode_folder / "settings.json"),
722 )?;
723 }
724
725 Ok((
726 project.dir.as_ref().into(),
727 project.target_dir.as_ref().into(),
728 project.features,
729 ))
730}
731
732fn check_contents(contents: &[u8], path: &Path) -> Result<bool, std::io::Error> {
733 let mut file = File::options()
734 .read(true)
735 .write(false)
736 .create(false)
737 .truncate(false)
738 .open(path)?;
739 file.lock()?;
740
741 let mut existing_contents = Vec::new();
742 file.read_to_end(&mut existing_contents)?;
743 Ok(existing_contents == contents)
744}
745
746pub(crate) fn write_atomic(contents: &[u8], path: &Path) -> Result<(), std::io::Error> {
747 let mut file = File::options()
748 .read(true)
749 .write(true)
750 .create(true)
751 .truncate(false)
752 .open(path)?;
753
754 let mut existing_contents = Vec::new();
755 file.read_to_end(&mut existing_contents)?;
756 if existing_contents != contents {
757 file.lock()?;
758 file.seek(SeekFrom::Start(0))?;
759 file.set_len(0)?;
760 file.write_all(contents)?;
761 }
762
763 Ok(())
764}