1use std::fmt::Write as FmtWrite;
25use std::fs;
26use std::path::{Path, PathBuf};
27use std::process::Command;
28
29use crate::compile::compile_project_with_deps;
30use logicaffeine_compile::compile::{copy_runtime_crates, CompileError, RuntimeCrateSource};
31
32use super::manifest::{Manifest, ManifestError};
33
34pub struct BuildConfig {
56 pub project_dir: PathBuf,
58 pub release: bool,
60 pub lib_mode: bool,
62 pub target: Option<String>,
65}
66
67#[derive(Debug, Clone, Copy, PartialEq, Eq)]
69pub enum Backend {
70 Rust,
72 C(super::build_c::CLowering),
74}
75
76impl Backend {
77 pub fn from_emit(emit: &str) -> Option<Self> {
79 match emit {
80 "c" => Some(Self::C(super::build_c::CLowering::Ast)),
81 "c-bytecode" => Some(Self::C(super::build_c::CLowering::Bytecode)),
82 _ => None,
83 }
84 }
85}
86
87#[derive(Debug)]
92pub struct BuildResult {
93 pub target_dir: PathBuf,
95 pub binary_path: PathBuf,
97}
98
99#[derive(Debug)]
101pub enum BuildError {
102 Manifest(ManifestError),
104 Compile(CompileError),
106 Diagnostic(String),
108 Io(String),
110 Cargo(CargoFailure),
113 Toolchain(String),
115 CToolchain(String),
117 CCompiler(String),
119 Unsupported(String),
121 NotFound(String),
123}
124
125impl std::fmt::Display for BuildError {
126 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
127 match self {
128 BuildError::Manifest(e) => write!(f, "{}", e),
129 BuildError::Compile(e) => write!(f, "{}", e),
130 BuildError::Diagnostic(rendered) => write!(f, "{rendered}"),
131 BuildError::Io(e) => write!(f, "IO error: {}", e),
132 BuildError::Cargo(e) => write!(f, "{}", e),
133 BuildError::Toolchain(e) => write!(f, "{}", e),
134 BuildError::CToolchain(e) => write!(f, "{}", e),
135 BuildError::CCompiler(e) => write!(f, "{}", e),
136 BuildError::Unsupported(e) => write!(f, "{}", e),
137 BuildError::NotFound(e) => write!(f, "Not found: {}", e),
138 }
139 }
140}
141
142impl std::error::Error for BuildError {}
143
144#[derive(Debug, Clone, Copy, PartialEq, Eq)]
147pub enum CargoFailureKind {
148 DependencyResolution,
151 GeneratedCode,
154}
155
156#[derive(Debug)]
160pub struct CargoFailure {
161 pub kind: CargoFailureKind,
163 pub tail: String,
165 pub project_dir: PathBuf,
167}
168
169impl std::fmt::Display for CargoFailure {
170 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
171 match self.kind {
172 CargoFailureKind::DependencyResolution => write!(
173 f,
174 "a `## Requires` dependency could not be resolved (cargo's output above has the details)"
175 ),
176 CargoFailureKind::GeneratedCode => write!(
177 f,
178 "the generated Rust failed to compile — this is a LOGOS compiler bug, not an error in your program (generated project: {})",
179 self.project_dir.display()
180 ),
181 }
182 }
183}
184
185pub fn requires_component_is_safe(s: &str) -> bool {
190 !s.is_empty()
191 && s.chars().all(|c| {
192 c.is_ascii_alphanumeric()
193 || matches!(
194 c,
195 '-' | '_' | '.' | '^' | '~' | '*' | '<' | '>' | '=' | '+' | ',' | ' '
196 )
197 })
198}
199
200pub fn classify_cargo_failure(stderr_tail: &str) -> CargoFailureKind {
207 const DEPENDENCY_MARKERS: [&str; 6] = [
208 "no matching package",
209 "failed to select a version",
210 "failed to get ",
211 "failed to fetch",
212 "failed to load source for dependency",
213 "unable to get packages from source",
214 ];
215 if DEPENDENCY_MARKERS.iter().any(|m| stderr_tail.contains(m)) {
216 CargoFailureKind::DependencyResolution
217 } else {
218 CargoFailureKind::GeneratedCode
219 }
220}
221
222impl From<ManifestError> for BuildError {
223 fn from(e: ManifestError) -> Self {
224 BuildError::Manifest(e)
225 }
226}
227
228impl From<CompileError> for BuildError {
229 fn from(e: CompileError) -> Self {
230 BuildError::Compile(e)
231 }
232}
233
234pub fn find_project_root(start: &Path) -> Option<PathBuf> {
255 let mut current = if start.is_file() {
256 start.parent()?.to_path_buf()
257 } else {
258 start.to_path_buf()
259 };
260
261 loop {
262 if current.join("Largo.toml").exists() {
263 return Some(current);
264 }
265 if !current.pop() {
266 return None;
267 }
268 }
269}
270
271fn plan_web_bundle(
279 project_dir: &Path,
280) -> Result<Option<Vec<crate::commands::web_bundle::Asset>>, BuildError> {
281 let embeds_site = super::shape::Project::load(project_dir)
284 .and_then(|project| project.shape())
285 .map(|shape| shape.build_plan() == super::shape::BuildPlan::Binary { embeds_site: true })
286 .unwrap_or(false);
287 if !embeds_site {
288 return Ok(None);
289 }
290 let assets = crate::commands::web_bundle::plan_site(
291 &project_dir.join("pages"),
292 &project_dir.join("static"),
293 )
294 .map_err(|e| BuildError::Io(e.to_string()))?;
295 Ok(Some(assets))
296}
297
298pub fn build(config: BuildConfig) -> Result<BuildResult, BuildError> {
317 build_backend(config, Backend::Rust)
318}
319
320pub fn build_backend(config: BuildConfig, backend: Backend) -> Result<BuildResult, BuildError> {
322 let manifest = Manifest::load(&config.project_dir)?;
324
325 let entry_path = super::shape::entry_file(&config.project_dir, &manifest)
328 .map_err(|e| BuildError::NotFound(e.message))?
329 .ok_or_else(|| {
330 BuildError::NotFound(super::shape::site_without_entry(&config.project_dir).message)
331 })?;
332 match backend {
333 Backend::Rust => build_with_entry(&config, &manifest, &entry_path),
334 Backend::C(lowering) => {
335 super::build_c::build_c_with_entry(&config, &manifest, &entry_path, lowering)
336 }
337 }
338}
339
340fn build_with_entry(
341 config: &BuildConfig,
342 manifest: &Manifest,
343 entry_path: &Path,
344) -> Result<BuildResult, BuildError> {
345 let started = std::time::Instant::now();
346 crate::ui::phase(
347 "Compiling",
348 format!(
349 "{} v{} (LOGOS → Rust)",
350 manifest.package.name, manifest.package.version
351 ),
352 );
353
354 let target_dir = config.project_dir.join("target");
356 let build_dir = if config.release {
357 target_dir.join("release")
358 } else {
359 target_dir.join("debug")
360 };
361 let rust_project_dir = build_dir.join("build");
362
363 if rust_project_dir.exists() {
365 fs::remove_dir_all(&rust_project_dir).map_err(|e| BuildError::Io(e.to_string()))?;
366 }
367 fs::create_dir_all(&rust_project_dir).map_err(|e| BuildError::Io(e.to_string()))?;
368
369 let site_assets = if config.lib_mode {
376 None
377 } else {
378 plan_web_bundle(&config.project_dir)?
379 };
380
381 let dep_roots = manifest
386 .resolve_dependencies(&config.project_dir)
387 .map_err(|e| BuildError::Io(e.to_string()))?
388 .into_iter()
389 .map(|d| logicaffeine_compile::loader::DepRoot {
390 name: d.name,
391 root: d.root,
392 })
393 .collect::<Vec<_>>();
394
395 let compiled = if site_assets.is_some() {
400 logicaffeine_compile::codegen::with_embed_assets(|| {
401 compile_project_with_deps(entry_path, dep_roots.clone())
402 })
403 } else {
404 compile_project_with_deps(entry_path, dep_roots.clone())
405 };
406 let output = compiled.map_err(|e| match e {
407 CompileError::Parse(_) => BuildError::Diagnostic(
408 crate::diagnostics::compile_error(&e, entry_path, &dep_roots).message,
409 ),
410 other => BuildError::Compile(other),
411 })?;
412
413 let src_dir = rust_project_dir.join("src");
415 fs::create_dir_all(&src_dir).map_err(|e| BuildError::Io(e.to_string()))?;
416
417 let rust_code = output.rust_code.clone();
418
419 if config.lib_mode {
420 let lib_code = strip_main_wrapper(&rust_code);
422 fs::write(src_dir.join("lib.rs"), lib_code).map_err(|e| BuildError::Io(e.to_string()))?;
423 } else if let Some(ref assets) = site_assets {
424 use crate::commands::web_bundle::{page_patterns, site_assets_module, staged_asset_files};
429 let patterns = page_patterns(&config.project_dir.join("pages"));
432 fs::write(
433 src_dir.join("logos_assets.rs"),
434 site_assets_module(&config.project_dir.join("pages"), assets, &patterns),
435 )
436 .map_err(|e| BuildError::Io(e.to_string()))?;
437 for (name, bytes) in staged_asset_files(assets) {
438 fs::write(src_dir.join(&name), bytes).map_err(|e| BuildError::Io(e.to_string()))?;
439 }
440 let main_code = format!("mod logos_assets;\n{rust_code}");
441 fs::write(src_dir.join("main.rs"), main_code).map_err(|e| BuildError::Io(e.to_string()))?;
442 } else {
443 fs::write(src_dir.join("main.rs"), &rust_code)
444 .map_err(|e| BuildError::Io(e.to_string()))?;
445 }
446
447 if let Some(ref c_header) = output.c_header {
449 let header_name = format!("{}.h", manifest.package.name);
450 fs::write(rust_project_dir.join(&header_name), c_header)
451 .map_err(|e| BuildError::Io(e.to_string()))?;
452 }
453
454 let resolved_target = config.target.as_deref().map(|t| {
456 if t.eq_ignore_ascii_case("wasm") {
457 "wasm32-unknown-unknown"
458 } else {
459 t
460 }
461 });
462
463 let identity = artifact_identity(&manifest.package.name, &config.project_dir);
468 let mut cargo_toml = format!(
469 r#"[package]
470name = "{}"
471version = "{}"
472edition = "2021"
473autobins = false
474"#,
475 manifest.package.name, manifest.package.version
476 );
477 if config.lib_mode {
478 let _ = writeln!(
479 cargo_toml,
480 "\n[lib]\nname = \"{}\"\npath = \"src/lib.rs\"\ncrate-type = [\"cdylib\"]",
481 identity.replace('-', "_")
482 );
483 } else {
484 let _ = writeln!(
485 cargo_toml,
486 "\n[[bin]]\nname = \"{identity}\"\npath = \"src/main.rs\""
487 );
488 }
489
490 let runtime_source = RuntimeCrateSource::detect();
493 let _ = writeln!(cargo_toml, "\n[dependencies]");
494 let _ = writeln!(cargo_toml, "{}", runtime_source.data_dep());
495 let _ = writeln!(
496 cargo_toml,
497 "{}",
498 runtime_source.system_dep(&["full", "http"])
499 );
500 let _ = writeln!(
501 cargo_toml,
502 "tokio = {{ version = \"1\", features = [\"rt-multi-thread\", \"macros\"] }}"
503 );
504
505 for line in logicaffeine_compile::compile::implied_crate_deps(&rust_code, &output.dependencies)
508 {
509 let _ = writeln!(cargo_toml, "{line}");
510 }
511
512 let mut has_wasm_bindgen = false;
514 if let Some(target) = resolved_target {
515 if target.starts_with("wasm32") {
516 let _ = writeln!(cargo_toml, "wasm-bindgen = \"0.2\"");
517 has_wasm_bindgen = true;
518 }
519 }
520
521 for dep in &output.dependencies {
525 if dep.name == "wasm-bindgen" && has_wasm_bindgen {
526 continue; }
528 if !requires_component_is_safe(&dep.name)
529 || !requires_component_is_safe(&dep.version)
530 || dep.features.iter().any(|f| !requires_component_is_safe(f))
531 {
532 return Err(BuildError::Compile(CompileError::Io(format!(
533 "`## Requires` declaration for '{}' contains characters that are not valid in a Cargo manifest",
534 dep.name
535 ))));
536 }
537 if dep.features.is_empty() {
538 let _ = writeln!(cargo_toml, "{} = \"{}\"", dep.name, dep.version);
539 } else {
540 let feats = dep
541 .features
542 .iter()
543 .map(|f| format!("\"{}\"", f))
544 .collect::<Vec<_>>()
545 .join(", ");
546 let _ = writeln!(
547 cargo_toml,
548 "{} = {{ version = \"{}\", features = [{}] }}",
549 dep.name, dep.version, feats
550 );
551 }
552 }
553
554 let _ = write!(cargo_toml, "\n{}", runtime_source.linux_engine_section());
555
556 let _ = writeln!(
558 cargo_toml,
559 "\n[profile.release]\nlto = true\nopt-level = 3\ncodegen-units = 1\npanic = \"{}\"\nstrip = true",
560 logicaffeine_compile::codegen::release_panic_strategy(&rust_code)
561 );
562
563 fs::write(rust_project_dir.join("Cargo.toml"), &cargo_toml)
564 .map_err(|e| BuildError::Io(e.to_string()))?;
565
566 if config.release && resolved_target.is_none() {
569 let cargo_config_dir = rust_project_dir.join(".cargo");
570 fs::create_dir_all(&cargo_config_dir).map_err(|e| BuildError::Io(e.to_string()))?;
571 fs::write(
572 cargo_config_dir.join("config.toml"),
573 "[build]\nrustflags = [\"-C\", \"target-cpu=native\"]\n",
574 )
575 .map_err(|e| BuildError::Io(e.to_string()))?;
576 }
577
578 if runtime_source.is_workspace() {
581 copy_runtime_crates(&rust_project_dir)?;
582 }
583
584 crate::ui::phase("Building", "generated Rust (cargo)");
588 let mut cmd = Command::new("cargo");
589 cmd.arg("build")
593 .arg("--message-format=json-render-diagnostics")
594 .current_dir(&rust_project_dir);
595 if config.release {
596 cmd.arg("--release");
597 }
598 if let Some(target) = resolved_target {
599 cmd.arg("--target").arg(target);
600 }
601 let color_arg = match anstream::AutoStream::choice(&std::io::stderr()) {
604 anstream::ColorChoice::Never => "never",
605 _ => "always",
606 };
607 cmd.arg("--color").arg(color_arg);
608 if crate::ui::is_quiet() {
609 cmd.arg("--quiet");
610 } else if crate::ui::verbosity() > 0 {
611 cmd.arg("--verbose");
612 }
613 cmd.stdout(std::process::Stdio::piped());
614 cmd.stderr(std::process::Stdio::piped());
615
616 let mut child = cmd.spawn().map_err(|e| {
617 if e.kind() == std::io::ErrorKind::NotFound {
618 BuildError::Toolchain(
619 "cargo was not found on PATH — a Rust toolchain is required for `largo build`"
620 .to_string(),
621 )
622 } else {
623 BuildError::Io(e.to_string())
624 }
625 })?;
626
627 const TAIL_CAP: usize = 64 * 1024;
630 let mut child_err = child.stderr.take().expect("stderr was piped");
631 let tee = std::thread::spawn(move || {
632 use std::io::{Read, Write};
633 let mut tail: Vec<u8> = Vec::new();
634 let mut buf = [0u8; 8192];
635 let mut err_out = std::io::stderr();
636 loop {
637 match child_err.read(&mut buf) {
638 Ok(0) | Err(_) => break,
639 Ok(n) => {
640 let _ = err_out.write_all(&buf[..n]);
641 let _ = err_out.flush();
642 tail.extend_from_slice(&buf[..n]);
643 if tail.len() > TAIL_CAP {
644 let cut = tail.len() - TAIL_CAP;
645 tail.drain(..cut);
646 }
647 }
648 }
649 }
650 tail
651 });
652
653 let mut child_out = child.stdout.take().expect("stdout was piped");
654 let messages = std::thread::spawn(move || {
655 use std::io::Read;
656 let mut all = String::new();
657 let _ = child_out.read_to_string(&mut all);
658 all
659 });
660
661 let status = child.wait().map_err(|e| BuildError::Io(e.to_string()))?;
662 let tail_bytes = tee.join().unwrap_or_default();
663 let messages = messages.join().unwrap_or_default();
664
665 if !status.success() {
666 let tail = String::from_utf8_lossy(&tail_bytes).into_owned();
667 let kind = classify_cargo_failure(&tail);
668
669 if kind == CargoFailureKind::GeneratedCode {
674 if let Ok(assembled) = logicaffeine_compile::analysis::assemble_project(&entry_path) {
675 if let Ok(remapped) = logicaffeine_compile::compile::remap_project_errors(
676 &assembled.source,
677 &rust_project_dir,
678 Some(&assembled.source_map),
679 ) {
680 if !remapped.is_empty() {
681 eprintln!("\n— in your LOGOS source —");
682 for err in &remapped {
683 eprintln!("{err}");
684 }
685 }
686 }
687 }
688 }
689
690 return Err(BuildError::Cargo(CargoFailure {
691 kind,
692 tail,
693 project_dir: rust_project_dir,
694 }));
695 }
696
697 crate::ui::phase(
698 "Finished",
699 format!(
700 "{} profile in {:.1}s",
701 if config.release { "release" } else { "dev" },
702 started.elapsed().as_secs_f64()
703 ),
704 );
705
706 let built = built_artifact(&messages, &identity, config.lib_mode).ok_or_else(|| {
710 BuildError::Io(format!(
711 "cargo finished but reported no {} named `{identity}`; its output is in {}",
712 if config.lib_mode { "library" } else { "binary" },
713 rust_project_dir.display()
714 ))
715 })?;
716 let built_name = built
717 .file_name()
718 .map(|n| n.to_string_lossy().into_owned())
719 .unwrap_or_default();
720 let stable_name = if config.lib_mode {
721 built_name.replacen(
722 &identity.replace('-', "_"),
723 &manifest.package.name.replace('-', "_"),
724 1,
725 )
726 } else {
727 built_name.replacen(&identity, &manifest.package.name, 1)
728 };
729 let binary_path = build_dir.join(&stable_name);
730 fs::copy(&built, &binary_path).map_err(|e| {
733 BuildError::Io(format!(
734 "the build succeeded but its artifact could not be published to {}: {e}\n\
735 The freshly built file is at {}. Anything at the stable path is from an EARLIER \
736 build — do not ship it.",
737 binary_path.display(),
738 built.display()
739 ))
740 })?;
741
742 if output.c_header.is_some() {
744 let header_name = format!("{}.h", manifest.package.name);
745 let src_header = rust_project_dir.join(&header_name);
746 if src_header.exists() {
747 let _ = fs::copy(&src_header, build_dir.join(&header_name));
748 }
749 }
750
751 if let Some(assets) = &site_assets {
755 crate::ui::phase(
756 "Bundled",
757 format!(
758 "{} embedded asset(s) — self-contained web server",
759 assets.len()
760 ),
761 );
762 }
763 if !config.lib_mode {
764 crate::ui::phase("Artifact", binary_path.display().to_string());
765 }
766
767 Ok(BuildResult {
768 target_dir: build_dir,
769 binary_path,
770 })
771}
772
773fn artifact_identity(name: &str, project_dir: &Path) -> String {
777 let dir = project_dir
778 .canonicalize()
779 .unwrap_or_else(|_| project_dir.to_path_buf());
780 let digest = crate::commands::web_bundle::content_hash(dir.to_string_lossy().as_bytes());
781 format!("{name}-{digest}")
782}
783
784fn built_artifact(messages: &str, identity: &str, lib: bool) -> Option<PathBuf> {
787 let lib_name = identity.replace('-', "_");
788 messages
789 .lines()
790 .filter_map(|line| serde_json::from_str::<serde_json::Value>(line).ok())
791 .filter(|m| m["reason"] == "compiler-artifact")
792 .filter(|m| {
793 let name = m["target"]["name"].as_str().unwrap_or("");
794 if lib {
795 name == lib_name
796 } else {
797 name == identity
798 }
799 })
800 .find_map(|m| {
801 if lib {
802 m["filenames"]
803 .as_array()?
804 .iter()
805 .filter_map(|f| f.as_str())
806 .find(|f| {
807 let f = f.to_ascii_lowercase();
808 f.ends_with(".so")
809 || f.ends_with(".dylib")
810 || f.ends_with(".dll")
811 || f.ends_with(".wasm")
812 })
813 .map(PathBuf::from)
814 } else {
815 m["executable"].as_str().map(PathBuf::from)
816 }
817 })
818}
819
820fn strip_main_wrapper(code: &str) -> String {
823 if let Some(main_pos) = code.find("fn main() {") {
825 let before_main = &code[..main_pos];
826 let after_opening = &code[main_pos + "fn main() {".len()..];
828 if let Some(close_pos) = after_opening.rfind('}') {
829 let main_body = &after_opening[..close_pos];
830 let dedented: Vec<&str> = main_body
832 .lines()
833 .map(|line| line.strip_prefix(" ").unwrap_or(line))
834 .collect();
835 format!("{}\n{}", before_main.trim_end(), dedented.join("\n"))
836 } else {
837 before_main.to_string()
838 }
839 } else {
840 code.to_string()
841 }
842}
843
844pub fn run(build_result: &BuildResult, args: &[String]) -> Result<i32, BuildError> {
861 let mut child = Command::new(&build_result.binary_path)
862 .args(args)
863 .spawn()
864 .map_err(|e| BuildError::Io(e.to_string()))?;
865
866 let status = child.wait().map_err(|e| BuildError::Io(e.to_string()))?;
867
868 Ok(status.code().unwrap_or(1))
869}
870
871#[cfg(test)]
872#[path = "../../../../crates/logicaffeine_tests/unit/logicaffeine_cli/project/build/tests.rs"]
873mod tests;